在构建捆绑包时如何删除未使用的代码?

bra*_*nne 9 javascript webpack

我不知道如何组织我的 js 代码。
我们的前端是针对不同客户定制的。大多数基本代码对于所有客户都是通用的。然而,在某些情况下,每个客户的某些功能都会被覆盖。
例如,如果我们有 2 个函数 Function1 和 Function2。
Customer1 使用 Function1,而 Customer2 使用 Function2。如何确保在为 Customer 构建代码时,Function2 不会包含在捆绑包中?当我为 Customer2 构建代码时,Function1 将不会包含在捆绑包中?

我想要避免的另一个选择是为每个客户提供单独的代码存储库。

Kin*_*one 8

在 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
        }
    }
];
Run Code Online (Sandbox Code Playgroud)

库.js

exports.usedFunction = () => {
    return 0;
};

exports.unusedFunction = () =>{
    return 1;
};
Run Code Online (Sandbox Code Playgroud)

main.js

// Not working
// const lib = require("./lib"); 
// const usedFunction = lib.usedFunction;

// Working
const usedFunction = require("./lib").usedFunction;

usedFunction()
```shell
$ webpack 
Run Code Online (Sandbox Code Playgroud)

生成的输出文件:
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)()})();
Run Code Online (Sandbox Code Playgroud)

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)()})();
                           ^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)


小智 3

我认为你需要的是webpack 中的Tree-Shaking