簡體   English   中英

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

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

我遵循了很多有關如何減小捆綁包大小的教程,但是對捆綁包大小沒有任何影響,我也不知道為什么。

每當我將一些新代碼添加到webpack時,我的捆綁包大小都與以前相同。

(我的應用程序是使用vue cli 3 pwa插件,webpack等構建的)

如果我運行npm run buildnpm run build得到以下輸出:

圖片

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()];
         }

Webpack團隊的Sean。 我會建議幾件事。

  1. 升級到webpack 4 (由於您正在使用CommonsChunkPlugin(),我可以告訴您是3)。 webpack 4附帶了大量的大小和構建時間性能。 默認情況下,新的vue-cli使用它。

  2. 代碼拆分您的路線和組件。 通過代碼拆分,您可以延遲加載JavaScript,直到以后需要它為止。 此技術減少了將要創建的初始捆綁包中的代碼量。 這是我的一個演講: 肖恩·托馬斯·拉金(Sean Thomas Larkin)和Vue的代碼分割模式

  3. 與使用代碼拆分相比,嘗試使用webpack配置永遠不會獲得真正的加載時性能!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM