Last active
October 1, 2024 05:42
-
-
Save 0x80/586283af54ff2b8a436a01a4b62bcea6 to your computer and use it in GitHub Desktop.
Vite bundling for a modern Node.js target
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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