Externalize library bundle dependencies
This is a follow-up to my post Vite/Rollup preserveModules for libraries.
In my previous post I talked about how to rename the node_modules
folder to external
to avoid the special properties of a node_modules folder.
Since that post I've found another way that actually makes a lot more sense.
Bundle or as dependency
Previously I was taking everything in node_modules
and including that in our bundle. However, after further thought, that doesn't really make sense. Why are we specifying dependencies, which will get installed with npm i
and bundling them. That means they will end up being included twice in the project we use our library in.
Instead we want to externalize all our dependencies.
import packageJson from "./package.json";const config = defineConfig({build: {lib: {entry: './src/index.ts',formats: ['es'],fileName: (format, entryName) =>`${entryName.replace(/node_modules\//g, 'external/')}.${format}.js`,},rollupOptions: {external: [...Object.keys(packageJson.dependencies),...Object.keys(packageJson.peerDependencies),],},},});
I'm still including the renaming of the node_modules
folder as I found there were still a few cases where it bundled dependencies. It think it has to do with subpath imports (eg. `import myFunction from "packagename/myFunction".
But that will be a post for another time.