7 min read
One package.json field cut 452 kB from our consumers’ bundles
Our styles package was missing the sideEffects declaration. One named import was pulling in 743 kB. The fix is a single line in package.json, but setting it to plain false will drop your CSS in webpack and rspack.
A team using our design system wanted to measure what our theme provider was adding to their bundle. They had a single named import in their app shell and nothing else. It resolved to 743 kB of minified JavaScript.
One line in package.json removed 452 kB (−61%) from that total.
import { AppThemeProvider } from '@acme/styles' | minified | gzip |
|---|---|---|
no sideEffects field | 743 kB | 148 kB |
"sideEffects": false | 291 kB | 58 kB |
| deep import of the component's own file | 291 kB | – |
These numbers come from the published packages, measured with esbuild 0.28.2. Inside the monorepo both versions were roughly 1.6 kB smaller (npm resolved different transitive versions), with the saving identical to the byte.
Almost every package in our component library has declared "sideEffects": false for years. The styles package was one of the few that never got the line, and it stayed that way for about a year without anyone noticing.
There is one important detail. Setting the field to plain false causes webpack and rspack to quietly drop CSS imports, even from modules that your consumers actually use. The webpack tree-shaking guide does mention this, but most brief articles about the field simply say to add false. esbuild keeps the CSS, so testing only with esbuild won’t surface the problem. This part matters, because it can break styles in a consumer’s application.
It never showed up in our own build
The field is metadata. Our library build output stays identical either way, so our per-file size reports stayed green the whole time. They couldn’t have caught it. The extra cost only appears when someone else bundles the package.
I reproduced a consumer bundle instead. In a clean project I installed the package the way a real user would (npm install @acme/styles esbuild) and bundled a one-line entry. The script below bundles both a root import and a deep import of the same named export, then compares the files included in each.
// check-barrel.mjs: run from a fixture project that depends on the package and esbuild.
import * as esbuild from 'esbuild';
const [pkg, name, deepPath, external = ''] = process.argv.slice(2);
const bundle = async (spec) => {
const { metafile } = await esbuild.build({
stdin: { contents: `import { ${name} } from '${spec}'; console.log(${name});`, resolveDir: process.cwd() },
bundle: true, minify: true, format: 'esm', outdir: 'out', write: false, metafile: true,
external: external.split(',').filter(Boolean), logLevel: 'silent',
});
const js = Object.values(metafile.outputs).find((o) => o.entryPoint);
const files = Object.keys(js.inputs).filter((f) => js.inputs[f].bytesInOutput > 0 && f !== '<stdin>');
return { bytes: js.bytes, files: new Set(files) };
};
const root = await bundle(pkg);
const deep = await bundle(`${pkg}/${deepPath}`);
const extra = [...root.files].filter((f) => !deep.files.has(f));
console.log(`root ${root.bytes} B, deep ${deep.bytes} B, extra files: ${extra.join(', ') || 'none'}`);
if (extra.length) {
console.error('The root import bundles files the deep import does not. Check "sideEffects".');
process.exit(1);
}
A few details tripped me up while writing it:
- The import must be used. The
console.log(${name})is deliberate. If the import is unused, esbuild drops everything the field permits. With the fix applied the bundle measured 0 B of JavaScript. outdiris required even whenwrite: false, as soon as any file in the graph imports CSS. Ours does.externalmust match the real host application. I externalized peer dependencies and one shared runtime dependency. Without any externals the bundle grew to about 12 MB and the measured saving became 479 kB, larger than any real consumer would see.
Where the 452 kB came from
The metafile showed exactly which input files contributed bytes. Of the extra 452 kB, 412 kB came from a handful of design-token JSON files and 39 kB from icons. The theme provider itself used none of them.
The tokens were pulled in by a theme-builder function that was also exported from the same barrel file. That module built a lookup table at the top level by passing each JSON file through a helper whose only job was to return its argument unchanged. A function that did nothing.
A top-level call is still a call. A bundler can only remove it if it can prove the call is pure. Without sideEffects, every module re-exported by the barrel has to be included and executed in case it has observable effects. The bundler couldn’t prove that for the lookup table.
Component libraries are full of these top-level calls: styled(), forwardRef(), memo(), createContext().
What the field actually promises
"sideEffects": false is a promise about modules. It tells the bundler that importing a file without using any of its exports produces no observable side effects. With that promise, the bundler can follow the re-export directly to the file that actually defines the thing you imported and skip everything else in the barrel, along with everything those other files import.
It makes no promises about code inside a module you do use. Consider this small example library where the consumer writes import { Button } from 'lib'; console.log(Button());:
// index.js
export * from './Button.js';
export * from './tokens.js';
export * from './register.js';
// Button.js
import './button.css';
const build = (tag) => Object.freeze({ tag });
export const Button = () => 'button';
export const plain = build('plain-call'); // plain call
export const pure = /* @__PURE__ */ build('pure-call'); // annotated call
// tokens.js
import base from './base.tokens.json'; // 43 kB
const asTokens = (json) => Object.freeze(json);
const TOKENS = { base: asTokens(base) };
export const getTokens = () => TOKENS.base;
// register.js
globalThis.__LIB_REGISTERED__ = true;
export const registerElements = () => {};
esbuild 0.28.2, webpack 5.108.4 and rspack 1.7.5 agreed on every row except the last. webpack and rspack were run in production mode with css-loader and their CSS extraction plugins:
import { Button } from 'lib' | no field | "sideEffects": false |
|---|---|---|
tokens.js and its JSON | kept | dropped |
register.js global assignment | kept | dropped |
unused plain in Button.js | kept | kept |
unused pure in Button.js | dropped | dropped |
button.css | kept | esbuild kept it; webpack and rspack dropped it |
The field removed entire unused modules. The plain call stayed because its containing module was already in the bundle. Dead code elimination inside a used module still requires /* @__PURE__ */ annotations (or a compiler that adds them). The sideEffects field doesn’t help there.
The top-level call was what kept the tokens alive. With a plain const TOKENS = { base } instead, all three bundlers dropped the JSON even without the field. The example uses Object.freeze because webpack’s minifier would inline a bare identity function and eliminate it anyway. esbuild and rspack kept it, exactly as happened in our real package.
When the promise breaks your app
Bundlers trust the declaration. If a module actually does have side effects on import, setting false removes that behavior with no error.
Bare imports. Anything loaded only for its side effects (polyfills, customElements.define, i18n setup, plugin registration) will be dropped if you use import 'pkg/register'. All three bundlers dropped import 'lib/register.js' when the field was false. esbuild emitted an ignored-bare-import warning. webpack and rspack stayed silent.
CSS. With false, webpack and rspack dropped import './button.css' from inside Button.js, even though Button.js was the module the consumer used. esbuild left it alone. That means an esbuild test fixture won’t reveal the breakage, but your webpack and rspack users will lose their styles.
The correct fix uses the array form that explicitly lists files allowed to have side effects:
"sideEffects": ["**/*.css", "./register.js"]
With this, all three bundlers kept the CSS and the bare register.js import while still dropping the tokens. Listing a file only preserves it where something imports it for its side effects; register.js reached through the barrel's re-export alone is still removed. If you also ship Sass sources, add "**/*.scss".
Keeping the fix from regressing
The actual change was one line in package.json, plus a small script that fails the build if any publishable package is missing the field:
// verify-side-effects.mjs: run from the monorepo root.
import fs from 'node:fs';
const NODE_ONLY = new Set(['@acme/scripts']); // tooling that never reaches a browser bundle
const missing = fs.readdirSync('packages', { withFileTypes: true })
.filter((entry) => entry.isDirectory() && fs.existsSync(`packages/${entry.name}/package.json`))
.map((entry) => JSON.parse(fs.readFileSync(`packages/${entry.name}/package.json`, 'utf8')))
.filter((pkg) => !pkg.private && !NODE_ONLY.has(pkg.name) && pkg.sideEffects === undefined)
.map((pkg) => pkg.name);
if (missing.length) {
console.error(`Missing "sideEffects" (false, or the files that have effects): ${missing.join(', ')}`);
process.exit(1);
}
We run it in CI. A check that only runs on a developer’s machine only catches the mistake for whoever happens to remember.
A simple presence check can’t tell you whether the value is correct. For that we also run check-barrel.mjs in CI. On the toy example:
$ node check-barrel.mjs lib Button Button.js # no sideEffects field: exit 1
root 39070 B, deep 81 B, extra files: node_modules/lib/base.tokens.json, node_modules/lib/tokens.js, node_modules/lib/register.js
The root import bundles files the deep import does not. Check "sideEffects".
$ node check-barrel.mjs lib Button Button.js # "sideEffects": ["**/*.css"]: exit 0
root 81 B, deep 81 B, extra files: none
Against our styles package the broken version listed 35 extra files; the fixed version listed none. The script deliberately compares sets of files rather than byte counts. On the current release both bundles contain the same files but differ by a few bytes because the minifier chooses different variable names. And because it uses esbuild, it will accept "sideEffects": false on the toy even though webpack and rspack would drop button.css. Always test CSS behavior with the bundlers your consumers actually use.
Checklist
- Every published
package.jsondeclaressideEffects:false, or an array listing CSS files and any file that sets globals, registers elements, patches prototypes or is documented as a bare import. - Size is measured from a consumer fixture whose
externallist matches the real host. - Root and deep imports produce the same set of files.
- CSS survival is tested with webpack or rspack, not only esbuild.
- Both checks run in CI.
If you had switched to deep imports because the barrel was heavy, it’s worth measuring again after the library ships the field. For our styles package the root import now pulls in the same files as the deep import, within about 200 B.
The entire fix was one line of JSON. Finding the problem required building a consumer’s bundle, because none of our own build tooling could see the cost.