What are usedExports and sideEffects?

1.9k Views Asked by At

What exactly is the difference between usedExports in optimization of webpack config and sideEffects in package.json?

1

There are 1 best solutions below

4
Harshal Patil On

These are two different things.

About the usedExports:

Consider this as an instruction to Webpack to allow it to do two things:

  • Allow the exported identifiers to be renamed to shorter version (name mangling), By default, during the bundling process, the exported modifiers are not renamed.
  • Allow unused exports to be not exported from a module. By default, all the exported identifiers (variables, functions, classes, etc.) are exported even if those are not used anywhere in code.

For example, in the code

// MODULE A
export const myVariable = 10;

export const myFunction1 = () => a1;

export const myFunction2 = () => a2();


// MODULE B
import { myVariable } from './a.js';

// MODULE C
import { myFunction1 } from './a.js';

With this flag enabled, in above code, since myFunction2 is not used anywhere in the code, it would not be exported when the a.js module is being exported. Next thing it would probably try is to rename myVariable to single letter identifier like a and myFunction1 to b or similar. This applies to not just the modules you have authored but also the modules from node_modules as well.

About the sideEffects:

Although module bundler like webpack is smart enough to figure out if there are side effect in a given module, providing explicit sideEffects hints adds more confidence for bundler.

When doing the production bundling, the sideEffects and usedExports is used only if optimization.providedExports flag is enabled.