Skip to content

Instantly share code, notes, and snippets.

@0x80
Last active October 1, 2024 05:42
Show Gist options
  • Save 0x80/586283af54ff2b8a436a01a4b62bcea6 to your computer and use it in GitHub Desktop.
Save 0x80/586283af54ff2b8a436a01a4b62bcea6 to your computer and use it in GitHub Desktop.
Vite bundling for a modern Node.js target
import { builtinModules } from "node:module";
import { resolve } from "node:path";
import { defineConfig } from "vite";
import { dependencies, name } from "./package.json";
/**
* Core modules could be imported in two ways, with or without the `node:`
* specifier, so we create a list of all possible core modules.
*/
const allCoreModules = builtinModules.flatMap((moduleName) => [
moduleName,
`node:${moduleName}`,
]);
const globalsForAllCoreModules = allCoreModules.reduce((acc, moduleName) => {
const [prefix, namePart] = moduleName.split(":");
acc[moduleName] = prefix === "node" ? namePart : moduleName;
return acc;
}, {} as Record<string, string>);
console.log("globalsForAllCoreModules", globalsForAllCoreModules);
/**
* Extract the external dependencies but keep monorepo workspace packages as part of
* the bundle.
*/
const externalDependencies = Object.entries(dependencies)
.filter(([, value]) => value !== "workspace:*")
.map(([key]) => key);
console.log("externalDependencies", externalDependencies);
export default defineConfig({
build: {
target: ["node18"],
lib: {
entry: resolve(__dirname, "src/index.ts"),
name,
fileName: "index",
formats: ["es"],
},
sourcemap: true,
outDir: "dist",
rollupOptions: {
external: [...allCoreModules, ...externalDependencies],
output: {
globals: globalsForAllCoreModules,
inlineDynamicImports: true,
},
},
},
resolve: {
alias: {
"~": resolve(__dirname, "./src"),
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment