Bundling a library for tree-shaking and multiple formats
library-mode bundler config.
externalize peers, emit ESM and CJS, preserve modules for tree-shaking, set sideEffects false, ship types.
bundling peers or shipping a single minified CJS blob.
WHAT THIS TESTS This verifies you know that bundling a library differs fundamentally from bundling an app: the output must let the consumer's bundler optimize, not pre-optimize for them.
A GOOD ANSWER COVERS Use the bundler's library mode. Externalize all peerDependencies and dependencies, react, react-dom, and any shared libs, so they are not inlined and consumers dedupe one copy. Output multiple formats: ESM for modern bundlers and tree-shaking, and CJS for older Node and tooling, declared via main, module, and a conditional exports map. Critically, preserve module structure with per-file output rather than concatenating into one file, because that, combined with sideEffects false in package.json (or an accurate list of files with side effects such as global CSS imports), lets the consumer's bundler drop unused components. Avoid aggressive minification of the published code; let the consumer minify. Generate .d.ts type declarations alongside. Optionally provide multiple entry points so importing one component does not pull the whole barrel.
COMMON WRONG ANSWERS Bundling react into the library, causing duplicate-React errors. Shipping only a single minified CJS blob, killing tree-shaking. Marking everything sideEffect-free when CSS imports actually have side effects, so styles get dropped. Forgetting type declarations.
LIKELY FOLLOW-UPS Why does ESM enable tree-shaking but CJS largely does not. What does sideEffects false do and when is it wrong. How do barrel files hurt tree-shaking.
ONE CONCRETE EXAMPLE You configure library mode to externalize react, emit dist ESM and CJS with preserved modules, set an exports map and sideEffects pointing only at the CSS files, and ship d.ts. A consumer importing only Button gets just Button in their bundle, while React stays their single shared copy.
Read the original → vite.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.