如何使用 Webpack 5 编写 Split Angular 11

Joe*_*oel 7 webpack code-splitting angular

在使用 Webpack 5 ( SplitChunksPlugin ) 对Angular 进行代码拆分时,互联网上似乎存在很大的空白

我已经阅读了谷歌搜索“代码拆分角度 webpack”的第一页和第二页上的几乎所有资源,其中包括反应教程。但是,我无法理解它的要点,因为那里有很多相互矛盾的方法。

我有一个这样的应用程序结构:

app/    
    modules/
        ...
        ...
        name/
            - name.component.ts
            - name.component.html
            - name.module.ts
            - name.service.ts
    app.module.ts
    app-routing.module.ts
    main.ts
    app.component.ts
app.js    
webpack.config.js
Run Code Online (Sandbox Code Playgroud)

我已经延迟加载了我的所有模块。现在我想对模块本身(组件及其依赖项等)进行代码拆分。

令我困惑的是“如何动态加载这些依赖项?”

我正在使用HtmlWebpackPlugin动态添加我生成的 javascript 到我的 index.html 文件。

Index.html

<body>
    <!-- outlet! -->
    <my-app></my-app>   
</body>
Run Code Online (Sandbox Code Playgroud)

HtmlWebpackPlugin已经产生了JavaScript的文件:

<body>
    <!-- outlet! -->
    <my-app></my-app>   
    <script type="text/javascript" src="/dist/main.bundle.js?7e402ab94c22169960b7"></script>
    <script type="text/javascript" src="/dist/vendor.bundle.js?7e402ab94c22169960b7"></script>
</body>
Run Code Online (Sandbox Code Playgroud)

main.bundle.js是我的项目代码,vendor.bundle.js而是 node_modules 等。

然而,这是一个相当大的项目,大约 23mb 的初始页面加载(是的,23 ...)这就是为什么我需要对这个项目进行代码拆分。

我的第一个问题是:由于所有内容(供应商和主包)都已加载到 index.html(其中包含我的路由器插座)。我如何从我的组件代码拆分我的依赖项?无论如何,它们最终都会出现在 Index.html 中,因为……那是路由器插座的位置?所以,用我目前的方法将我的 js 代码分成多少块并不重要。

webpack.config.js

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const sourcePath = path.join(__dirname, './public');
const destPath = path.join(__dirname, './public/dist');
const nodeModulesPath = path.join(__dirname, './node_modules');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
 
module.exports = function (env) {
    const nodeEnv = env && env.prod ? 'production' : 'development';
    const isProd = nodeEnv === 'production';
    const plugins = [      
        new webpack.EnvironmentPlugin({
            NODE_ENV: nodeEnv,
        }),
        // new BundleAnalyzerPlugin(),
        new webpack.NamedModulesPlugin(),
        new webpack.IgnorePlugin(/\.\/locale$/),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            Popper: ['popper.js', 'default']
        }),
        new HtmlWebpackPlugin({
            hash: true,
            template: sourcePath + '/index.html',
            filename: sourcePath + '/dist/index.html'
        })
    ];

    if (isProd) {
        plugins.push(
            new webpack.LoaderOptionsPlugin({
                minimize: true,
                debug: false
            }),
            new webpack.optimize.UglifyJsPlugin({
                compress: {
                    warnings: false,
                    screw_ie8: true,
                    conditionals: true,
                    unused: true,
                    comparisons: true,
                    sequences: true,
                    dead_code: true,
                    evaluate: true,
                    if_return: true,
                    join_vars: true,
                },
                output: {
                    comments: false,
                },
            })
        );
    }

    return {
        mode: 'development',
        devtool: isProd ? 'source-map' : 'eval',
        context: nodeModulesPath,
        entry: {
            main: sourcePath + '/main.ts',
            vendor: [
                'bootstrap/dist/css/bootstrap.min.css',
                'bootstrap/dist/js/bootstrap.min.js',
                'moment/min/moment-with-locales.js',
                'js-cookie/src/js.cookie.js',
                'lodash/lodash.js',
                'font-awesome/css/font-awesome.css',
                '@fortawesome/fontawesome-free/css/all.css',
                'admin-lte/dist/css/AdminLTE.css',
                'admin-lte/dist/css/skins/skin-blue.css'
            ]
        },
        optimization: {
            splitChunks: {
              chunks: 'async',
              minSize: 30000,
              maxSize: 0,
              minChunks: 2,
              maxAsyncRequests: 5, 
              maxInitialRequests: 3,
              automaticNameDelimiter: '~',
              name: true,
              cacheGroups: {
                vendors: {
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10
                },
                default: {
                  minChunks: 2,
                  priority: -20,
                  reuseExistingChunk: true
                }
              }
            }
          },
        output: {
            path: destPath,
            filename: '[name].bundle.js',
            chunkFilename: '[name]-chunk.js',
            publicPath: '/dist/'
        },

        module: {
            rules: [
                {
                    test: /\.ts$/,
                    exclude: /node_modules/,
                    use: [{

                        loader: 'ts-loader',
                        options: {
                            transpileOnly: true // https://github.com/TypeStrong/ts-loader#faster-builds
                          }
                    }
                    ],
                },
                {
                    test: /\.css$/,
                    use: [
                        'style-loader',
                        'css-loader'
                    ]
                },
                {
                    test: /\.(png|gif|jpg|woff|woff2|eot|ttf|svg)$/,
                    loader: 'url-loader?limit=100000'
                },
                {
                    test: require.resolve('jquery'),
                    use: [
                        { loader: 'expose-loader', options: 'jQuery' },
                        { loader: 'expose-loader', options: '$' }
                    ]
                }
            ],
        },
        resolve: {
            extensions: ['.js', '.ts'],
            modules: [
                path.resolve(__dirname, 'node_modules'),
            ],
            alias: {

            }
        },

        plugins: plugins,

        performance: isProd && {
            maxAssetSize: 100,
            maxEntrypointSize: 300,
            hints: 'warning',
        },

        stats: {
            warnings: false,
            colors: {
                green: '\u001b[32m',
            }
        }
    };
};
Run Code Online (Sandbox Code Playgroud)

我基本上想拆分每个模块的所有依赖项(即我上面称为 的组件文件夹name)。我将如何做到这一点?(或者……我有什么选择?)

数据&工作流程:

 1. User opens website. Default dependencies are loaded.
 2. User navigates to /dashboard
 3. Resources (node_modules & other dependencies) for /dashboard is loaded
Run Code Online (Sandbox Code Playgroud)

GIF取自该反应文章示出了它很好(装入块依赖性该模块)。