首页 > 解决方案 > 如何在 Webpack 中使用代码拆分来自定义输出?

问题描述

目前我的所有应用程序只有一个捆绑JS(我知道这很糟糕......)。我想使用 Webpack 的代码拆分来优化它,但我无法成功地做我想做的事。

我有我的主要 app.js 文件:

import './components/cookie';
import './components/accordion';
import './components/sidenav';
import './components/product';
etc.

我想为与个人资料页面相关的所有组件创建一个新文件。所以我从主 app.js 中导入了这些内容,并将其放入新的 profile.js 中:

import './profile';
import './order';
import './payment';
import './address';
import './subscription';

现在,我想在输出中有 2 个文件:

  1. 包含所有供应商的主 app.js
  2. profile.js 将仅包含与配置文件相关的 JS,并将从 app.js 加载共享供应商。如果有任何与 profile.js 本身相关的供应商,则应将它们直接包含在此文件中。

在某些情况下,app.js 将加载到所有页面上,而 profile.js 将仅加载到特定页面上。

但目前我只能有这些输出:

                 Asset      Size               Chunks             Chunk Names
                app.js   225 KiB                  app  [emitted]  app
        app~profile.js   105 KiB          app~profile  [emitted]  app~profile
            profile.js   112 KiB              profile  [emitted]  profile
        vendors~app.js  34.2 KiB          vendors~app  [emitted]  vendors~app
vendors~app~profile.js   524 KiB  vendors~app~profile  [emitted]  vendors~app~profile
Entrypoint app = vendors~app~profile.js vendors~app.js app~profile.js app.js
Entrypoint profile = vendors~app~profile.js app~profile.js profile.js

我的 webpack.config 如下:

module.exports = {
    entry: {
        app: './app/js/app.js',
        profile: './app/js/components/profile/_all.js'
    },
    mode: 'development',
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'public/scripts/')
    },
    optimization: {
        splitChunks: {
            chunks: 'all'
        }
    }
};

有什么方法可以首先获得我想要的输出?还是我没有以正确的方式思考这种代码拆分?

标签: javascriptoptimizationwebpackchunkscode-splitting

解决方案


推荐阅读