tree_shaking/no-side-effects-in-initialization Nursery ​
What it does ​
Marks all side-effects in module initialization that will interfere with tree-shaking.
This plugin is intended as a means for library developers to identify patterns that will interfere with the tree-shaking algorithm of their module bundler (i.e. rollup or webpack).
Why is this bad? ​
Side-effects in module initialization can hinder tree-shaking, which aims to remove unused code. If side-effects exist, it's harder for the bundler to safely eliminate code, leading to larger bundles and potentially unexpected behavior. Ensuring minimal side-effects allows bundlers to optimize code effectively.
Examples ​
Examples of incorrect code for this rule:
myGlobal = 17; // Cannot determine side-effects of assignment to global variable
const x = { [globalFunction()]: "myString" }; // Cannot determine side-effects of calling global function
Examples of correct code for this rule:
const localVar = 17; // Local variable assignment, no global side-effects
export default 42; // Pure export with no side-effects
Options ​
{
"rules": {
"tree-shaking/no-side-effects-in-initialization": [
2,
{
"noSideEffectsWhenCalled": [
// If you want to mark a function call as side-effect free
{ "function": "Object.freeze" },
{
"module": "react",
"functions": ["createContext", "createRef"]
},
{
"module": "zod",
"functions": ["array", "string", "nativeEnum", "number", "object", "optional"]
},
{
"module": "my/local/module",
"functions": ["foo", "bar", "baz"]
},
// If you want to whitelist all functions of a module
{
"module": "lodash",
"functions": "*"
}
]
}
]
}
}
Magic Comments ​
Besides the configuration, you can also use magic comments to mark a function call as side effect free.
By default, imported functions are assumed to have side-effects, unless they are marked with a magic comment:
import { /* tree-shaking no-side-effects-when-called */ x } from "./some-file";
x();
@__PURE__
is also supported:
import { x } from "./some-file";
/*@__PURE__*/ x();