Webpack 4 对标记sideEffects: false的包有哪些要求?
sideEffects: false的包的要求 Great question! When you mark a package with sideEffects: false in its package.json, Webpack 4 expects a few key things to safely apply its tree-shaking optimizations. Let's break them down:
No unintended side effects in code
This is the core requirement. A "side effect" here refers to code that affects the global environment without being explicitly exported or called—things like modifying global variables, manipulating the DOM on import, or executing top-level code that changes state outside the module. Webpack will aggressively tree-shake unused parts of your package ifsideEffects: falseis set, so any hidden side effects will break your app once those modules are removed.Correct
package.jsondeclaration
ThesideEffectsflag must be properly defined in the rootpackage.jsonof your package. Set it tofalseonly if every file in the package has no side effects. If some files do have unavoidable side effects, you can specify an array of paths instead (e.g.,"sideEffects": ["./src/global-styles.css", "./src/init.js"]), butfalsemeans the entire package is side-effect-free.Use ES Module (ESM) syntax
Webpack's tree-shaking works best with ESM (import/exportsyntax) because CommonJS modules have dynamic behaviors that make it hard to reliably detect side effects. Popular libraries like lodash-es and RxJS adopted ESM alongside thesideEffectsflag to enable maximum optimization—so your package should follow suit if you want Webpack to fully leverage this feature.Compatible dependency chain
If your package relies on other libraries, those dependencies should also handle side effects correctly. If a dependency has unmarked side effects, it could interfere with Webpack's ability to optimize your package properly. Sticking to updated versions of dependencies that supportsideEffectsis a good practice here.
From the Webpack 4 Release Announcement
过去30天里,我们与各框架紧密合作,确保它们能在各自的CLI等工具中支持Webpack 4。lodash-es、RxJS这类热门库也已支持sideEffects标记,使用其最新版本可立即减小打包体积。
内容的提问来源于stack exchange,提问作者Undistraction

