我不知道如何组织我的 js 代码。
我们的前端是针对不同客户定制的。大多数基本代码对于所有客户都是通用的。但是,在某些情况下,每个客户的某些功能都会被覆盖。
例如,如果我们有 2 个函数 Function1 和 Function2。
Customer1 使用 Function1,而 Customer2 使用 Function2。如何确保在为 Customer 构建代码时,Function2 不会包含在 bundle 中?当我为 Customer2 构建代码时,Function1 将不会包含在 bundle 中?
我想要避免的另一个选择是为每个客户提供单独的代码存储库。
最佳答案
在 webpack 配置中,optimization/usedExports: true将删除未使用的代码。
webpack.config.js
module.exports = [
{
entry: "./main.js",
output: {
filename: "output.js"
},
optimization: {
usedExports: true, // <- remove unused function
}
},
{
entry: "./main.js",
output: {
filename: "without.js"
},
optimization: {
usedExports: false, // <- no remove unused function
}
}
];
lib.js
exports.usedFunction = () => {
return 0;
};
exports.unusedFunction = () =>{
return 1;
};
main.js
// Not working
// const lib = require("./lib");
// const usedFunction = lib.usedFunction;
// Working
const usedFunction = require("./lib").usedFunction;
usedFunction()
```shell
$ webpack
<小时/>
生成的输出文件:
dist/output.js
(()=>{var r={451:(r,t)=>{t.W=()=>0}},t={};(0,function e(o){var n=t[o];if(void 0!==n)return n.exports;var p=t[o]={exports:{}};return r[o](p,p.exports,e),p.exports}(451).W)()})();
dist/without.js
(()=>{var n={451:(n,r)=>{r.usedFunction=()=>0,r.unusedFunction=()=>1}},r={};(0,function t(u){var e=r[u];if(void 0!==e)return e.exports;var o=r[u]={exports:{}};return n[u](o,o.exports,t),o.exports}(451).usedFunction)()})();
^^^^^^^^^^^
关于javascript - 在构建 bundle 时如何删除未使用的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58390116/