跳至內容

tree_shaking/no-side-effects-in-initialization 孵化中

作用

標記模組初始化中所有會干擾 tree-shaking 的副作用。

這個外掛程式旨在讓函式庫開發人員識別會干擾其模組打包工具 (例如 rollup 或 webpack) 的 tree-shaking 演算法的模式。

為什麼這不好?

模組初始化中的副作用會阻礙 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();

參考

根據 MIT 授權發布。