简体   繁体   English

如何在WEBPACK + VUEJS中减小包大小

[英]How to reduce bundle size in WEBPACK + VUEJS

I followed a lot of tutorials on how to reduce the bundle size, but nothing took any effect on the bundle size and I don't know why. 我遵循了很多有关如何减小捆绑包大小的教程,但是对捆绑包大小没有任何影响,我也不知道为什么。

Every time when I add some new code to webpack, my bundle size stays the same as before. 每当我将一些新代码添加到webpack时,我的捆绑包大小都与以前相同。

(My app is built with vue cli 3 pwa plugin, webpack... and so on) (我的应用程序是使用vue cli 3 pwa插件,webpack等构建的)

If I run npm run build , I'm getting this output: 如果我运行npm run buildnpm run build得到以下输出:

图片

webpack.config.js: webpack.config.js:

    const path = require('path');
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
    const OfflinePlugin = require('offline-plugin');
    const webpack = require('webpack');
    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    const WebpackChunkHash = require('webpack-chunk-hash');
    const CompressionPlugin = require('compression-webpack-plugin');

    if (process.env.NODE_ENV === 'production') {
        module.exports.plugins = (module.exports.plugins || []).concat([
            // or use push because it's faster
            new webpack.DefinePlugin({
                'process.env': {
                    'process.env.NODE_ENV': '"production"',
                },
            }),
            new webpack.optimize.UglifyJsPlugin({
                mangle: true,
                compress: {
                    warnings: false, // Suppress uglification warnings
                    pure_getters: true,
                    unsafe: true,
                    unsafe_comps: true,
                    screw_ie8: true,
                },
                output: {
                    comments: false,
                },
                exclude: [/\.min\.js$/gi], // skip pre-minified libs
            }),
            new webpack.HashedModuleIdsPlugin(),
            new WebpackChunkHash(),
            new CompressionPlugin({
                asset: '[path].gz[query]',
                algorithm: 'gzip',
                test: /\.js$|\.css$|\.html$/,
                threshold: 10240,
                minRatio: 0,
            }),
        ]);
    }

    const config = (module.exports = {
        mode: 'production',
        devtool: '', // Removed dev-tools mapping
        entry: [
            './src/app.js',
            {
                vendor: ['offline-plugin/runtime'],
            },
        ],
        output: {
            filename: '[name].bundle.js',
            path: path.resolve(__dirname, 'build/client'),
            publicPath: 'build/client',
        },
        resolve: {
            extensions: ['.js', '.vue', '.json'],
            alias: {
                vue$: 'vue/dist/vue.esm.js', // Use the full build
            },
        },
        module: {
            rules: [
                {
                    test: /\.vue$/,
                    use: 'vue-loader',
                },
                {
                    test: /\.css$/,
                    use: [
                        {
                            loader: MiniCssExtractPlugin.loader,
                            options: {
                                // you can specify a publicPath here
                                // by default it use publicPath in webpackOptions.output
                                publicPath: '../',
                            },
                        },
                        'vue-loader',
                    ],
                },
            ],
        },
        optimization: {
            runtimeChunk: {
                name: 'runtime',
            },
            splitChunks: {
                chunks: 'all',
                maxInitialRequests: Infinity,
                minSize: 0,
                cacheGroups: {
                    vendor: {
                        test: /[\\/]node_modules[\\/]/,
                        name(module) {
                            // get the name. E.g. node_modules/packageName/not/this/part.js
                            // or node_modules/packageName
                            const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

                            // npm package names are URL-safe, but some servers don't like @ symbols
                            return `npm.${packageName.replace('@', '')}`;
                        },
                    },
                },
            },
        },
        plugins: [
            new webpack.ContextReplacementPlugin(/moment[\\/]locale$/, /^\.\/(en|zh-tw)$/),
            new webpack.optimize.ModuleConcatenationPlugin(),
            new BundleAnalyzerPlugin(),
            new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]),
            new OfflinePlugin({
                AppCache: false,
                // important for working 200 respons => index.html ./
                externals: ['./'],
                ServiceWorker: {
                    events: true,
                },
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: 'vendor',
                minChunks: function(module) {
                    return module.context && module.context.indexOf('node_modules') !== -1;
                },
            }),
            new MiniCssExtractPlugin({
                // Options similar to the same options in webpackOptions.output
                // both options are optional
                filename: '[name].css',
                chunkFilename: '[id].css',
            }),
        ],
        });

        if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 
          'test') 
         {
          config.plugins = [...config.plugins, new BundleAnalyzerPlugin()];
         }

Sean from the webpack team. Webpack团队的Sean。 There's a couple of things I would recommend. 我会建议几件事。

  1. Upgrade to webpack 4 (I can tell you are on 3 because you are using CommonsChunkPlugin()). 升级到webpack 4 (由于您正在使用CommonsChunkPlugin(),我可以告诉您是3)。 webpack 4 shipped with a massive amount of size and build time performances. webpack 4附带了大量的大小和构建时间性能。 The new vue-cli uses it by default. 默认情况下,新的vue-cli使用它。

  2. Code Split your routes, and components. 代码拆分您的路线和组件。 Code-splitting lets you lazy load JavaScript until it is needed at a later time. 通过代码拆分,您可以延迟加载JavaScript,直到以后需要它为止。 This technique reduces the amount of code in the initial bundles that would be created. 此技术减少了将要创建的初始捆绑包中的代码量。 Here's a talk I gave about this: Code Splitting Patterns with Vue with Sean Thomas Larkin . 这是我的一个演讲: 肖恩·托马斯·拉金(Sean Thomas Larkin)和Vue的代码分割模式

  3. Trying to play around with the webpack configuration is never going to get you real load-time performance compared to using code-splitting!!! 与使用代码拆分相比,尝试使用webpack配置永远不会获得真正的加载时性能!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM