gpt4 book ai didi

Webpack tree-shaking removes side-effects code(Webpack摇树去掉副作用代码)

转载 作者:bug小助手 更新时间:2023-10-25 22:25:36 24 4
gpt4 key购买 nike



I was testing out webpack tree-shaking behavior. As per the docs, any code that contains side-effects can be mentioned in the sideEffects property of package.json to inform webpack not to eliminate that module in the final build. I am leveraging this behavior to see if my entire module (helper.js) can be part of the final build, even though all the exported methods of that module are not used.

我在测试webpack的摇树行为。根据文档,任何包含副作用的代码都可以在Package.json的SideEffects属性中提及,以通知webpack不要在最终构建中删除该模块。我利用这个行为来查看我的整个模块(helper.js)是否可以成为最终构建的一部分,即使该模块的所有导出方法都没有使用。


But in my case, this module is still getting tree-shaken. Can someone tell me what the reason might be?

但在我的情况下,这个模块仍在摇摇欲坠。谁能告诉我可能的原因是什么?


Here is my code:

以下是我的代码:


helper.js file

Helper.js文件


export default {
helperMethod1: () => {
console.log("This is helper method 1");
},
helperMethod2: () => {
console.log("This is helper method 2");
}
};

script.js

Script.js


import helper from "./helper.js";
helper.helperMethod1()

package.json

Package.json


{
"scripts": {
"build": "NODE_ENV=production webpack"
},
"sideEffects": ["./helper.js"],
...
}

webpack.config.js

Webpack.config.js


module.exports = {
...
optimization: {
sideEffects: true,
}
}

Here is the final production build

以下是最终的生产版本


(()=>{"use strict";console.log("This is a helper method 1")})();

I want helperMethod2 to also be part of the final build. I know this is against optimization, but I just want to better understand webpack's tree-shaking behavior.

我希望helperMethod2也成为最终构建的一部分。我知道这不利于优化,但我只是想更好地理解webpack的摇树行为。


更多回答

The way it is meant to work is when helper.js is its own npm module with its own package.json. Then you need to set sideEffect: true (not an array of strings) in that package.json not in the package.json of your main project.See github.com/webpack/webpack/blob/main/examples/side-effects/…

当helper.js是自己的NPM模块和自己的Package.json时,它的工作方式就是这样。然后,您需要在该Package.json中(而不是在主项目的Package.json中)设置SideEffect:True(不是字符串数组)。请参见github.com/webpack/webpack/blob/main/examples/side-effects/…

Got it. Thanks for clarifying. Will try this out.

明白了。谢谢你的澄清。会试一试这个。

优秀答案推荐
更多回答

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com