tree_shaking/no-side-effects-in-initialization Nursery
作用
标记模块初始化中会干扰 tree-shaking 的所有副作用。
此插件旨在作为一种手段,让库开发者识别到会干扰其模块打包器(如 rollup 或 webpack)的 tree-shaking 算法的模式。
为什么这样做有坏处?
模块初始化中的副作用可能会阻碍 tree-shaking,后者旨在去除未使用的代码。如果存在副作用,打包器就更难安全删除代码,从而导致更大的包,并可能出现意外行为。确保最小化副作用能让打包器有效优化代码。
示例
此规则不正确代码的示例
JavaScript
myGlobal = 17; // Cannot determine side-effects of assignment to global variable
const x = { [globalFunction()]: "myString" }; // Cannot determine side-effects of calling global function
此规则正确代码的示例
JavaScript
const localVar = 17; // Local variable assignment, no global side-effects
export default 42; // Pure export with no side-effects
选项
JSON
{
"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": "*"
}
]
}
]
}
}
魔术注释
除了配置外,你还可以使用魔术注释将函数调用标记为无副作用。
默认情况下,导入的函数假定具有副作用,除非用魔术注释标记。
JS
import { /* tree-shaking no-side-effects-when-called */ x } from "./some-file";
x();
@__PURE__
也受支持
JS
import { x } from "./some-file";
/*@__PURE__*/ x();