// package.json of a library
{
"name": "my-ui-kit",
"module": "dist/index.mjs",
"sideEffects": ["*.css"]
}
Tree shaking needs ES modules, and it needs to know that dropping a module is safe. Tree shaking means the bundler removes code that nothing imports.
Why ES modules? import and export are static. The bundler can read them at build time and see exactly which exports are used. CommonJS (require and module.exports) can be computed at run time, so the bundler can't be sure, and it keeps everything.
Why side effects block it. A side effect is code that does something when the file is first loaded, not only when you call an export. Examples:
- a polyfill that patches
Array.prototype import "./styles.css"- code that registers a plugin or sets a global
If a module might have side effects, the bundler must keep it, even when you use none of its exports. Removing it could change how the app behaves.
How a library tells the bundler it is safe:
"sideEffects": falseinpackage.jsonsays no file has side effects.- A list, like
["*.css"]above, says only those files do. - A
/*#__PURE__*/comment before a call says the result can be dropped if it is unused.
Tree shaking also only works in production builds, after minification removes the dead code.
- Tree shaking removes code that nothing imports.
- It needs static ES module
importandexport, so CommonJS usually can't be tree-shaken well. - A side effect is code that runs when the file is loaded, such as a polyfill or a CSS import.
- The bundler must keep any module that might have side effects.
- The
sideEffectsfield inpackage.jsontells the bundler which files are safe to drop.