How To Code Split Angular 11 With Webpack 5
Asked Answered
P

0

9

There seems to be a big vacuum on the internet when it comes to code-splitting Angular using Webpack 5 (SplitChunksPlugin).

I've read pretty much all resources on the first and second page of googling "code splitting angular webpack", that includes the tutorials for react. However, I cannot grasp the gist of it since there are a lot of contradictary approaches out there.

I've got an app structure like this:

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

I've already lazy-loaded all of my modules. Now I want to code-split both the module itself (component and its dependencies etc).

What is confusing me is "how do I load these dependencies dynamically?"

I'm using HtmlWebpackPlugin to dynamically add my generated javascript to my index.html file.

Index.html:

<body>
    <!-- outlet! -->
    <my-app></my-app>   
</body>

After HtmlWebpackPlugin has generated the javascript-files:

<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>

main.bundle.js is my project-code whilst vendor.bundle.js is node_modules etc.

However, this is quite a large project, ~23mb initial page-load (yes, 23...) Which is why I need to code-split this project.

My first question is: Since everything(vendor&main bundle) is already loaded in index.html (which contains my router-outlet). How do I code-split my dependencies from my components? They're all gonna end up in Index.html anyway, since.. that's where the router-outlet is? So, it doesn't matter how many chunks I divide my js-code into with my current approach.

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',
            }
        }
    };
};

I basically want to split all dependencies for EACH module (i.e my component-folder above called name). How would I accomplish this? (Or... what are my options?)

Process of data&workflow:

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

This GIF taken from this react article illustrates it well (Loading the chunk-dependencies for that module).

Presentable answered 7/2, 2019 at 10:13 Comment(5)
why doesn't use angular-cli, which is the official build tools based on webpack?Doerrer
I'm also interesting in this. This might be one way to go: blog.angularindepth.com/…Kirtley
@Doerrer do you incase know how to cache js with angular. cli?Karyotype
@Karyotype what do you mean? do you mean incremental build with angular-cli ?Doerrer
@Doerrer I had it sorted out, just add to HTML directly, thanks for the replyKaryotype

© 2022 - 2024 — McMap. All rights reserved.