webpack 打包優化

體積篇

一、初始狀態

2. router 按需加載

最後修改router.js,將全部路由都改成動態加載css

//router.js

//原來的寫法:import Home from '@/components/PC/Home'
//改爲下面這種形式(其餘路由同理)
const Home = () => import('@/components/PC/Home') 

複製代碼

3.添加dll

新增webpack.dll.conf.js 文件 Dll打包之後是獨立存在的,只要其包含的庫沒有增減、升級,hash也不會變化,所以線上的dll代碼不須要隨着版本發佈頻繁更新。html

App部分代碼修改後,只須要編譯app部分的代碼,dll部分,只要包含的庫沒有增減、升級,就不須要從新打包。這樣也大大提升了每次編譯的速度。vue

假設你有多個項目,使用了相同的一些依賴庫,它們就能夠共用一個dllnode

const path = require('path');
const webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    mode: 'none',
    entry: {
        vue: ['vue/dist/vue.js', 'vue', 'vue-router', 'vuex'],
        comment: ['jquery', 'lodash', 'jquery/dist/jquery.js']
    },
    output: {
        path: path.join(__dirname, '../static/dll/'),
        filename: '[name].dll.js',
        library: '[name]'
    },
    plugins: [
        new webpack.DllPlugin({
            path: path.join(__dirname, '../static/dll/', '[name]-manifest.json'),
            name: '[name]'
        })
    ],
    optimization: {
        minimizer: [
            new UglifyJsPlugin()
        ]
    }
};

複製代碼

執行命令,生產dll json webpack --config config/webpack.dll.conf.jsjquery

util.js plugins 添加webpack

new webpack.DllReferencePlugin({
            manifest: require('../static/dll/vue-manifest.json')
        }),

        new webpack.DllReferencePlugin({
            manifest: require('../static/dll/comment-manifest.json')
        })

複製代碼

index.html 添加文件鏈接es6

<script src="/static/dll/vue.dll.js"></script>
        <script src="/static/dll/comment.dll.js"></script>

複製代碼

4.添加SplitChunksPlugin

提取node_modules 初始化模塊,並設置緩存web

optimization: {
        splitChunks: {
            chunks: 'all',
            minChunks: 3,
            cacheGroups: {
                vendor: {
                    test: /node_modules/,
                    chunks: 'initial',
                    name: 'vendor',
                    priority: 10,
                    enforce: true
                }
            }
        }
    },

複製代碼

5.提取css

{
            test: /\.css$/,
            use: [
                MiniCssExtractPlugin.loader,
                'css-loader'
            ]
        }

複製代碼
new MiniCssExtractPlugin({
            filename: isBuild? 'css/[name].css':'css/[name]_[hash].css'
        })

複製代碼

5.提取element ui

element: {
                    test: /node_modules\/element-ui/,
                    chunks: 'initial',
                    name: 'element',
                    priority: 10,
                    enforce: true
                },

複製代碼
new HtmlWebpackPlugin({
            template: './pages/index.html',
            chunks: ['vendor', 'app', 'element']
        })

複製代碼

6.按需加載babel-polyfill

babel-polyfill的缺點 使用後打包後的體積很大,由於babel-polyfill是一個總體,把全部方法都加到原型鏈上。好比咱們只使用了Array.from,但它把Object.defineProperty也給加上了,這就是一種浪費了。 使用@babel/runtime和@babel/plugin-transform-runtime 用插件後,Babel就會使用babel@runtime下的工具函數,將Promise重寫成_Promise(只是打比方),而後引入_Promise helper函數。這樣就避免了重複打包代碼和手動引入模塊的痛苦。vue-router

.babelvuex

"plugins": [
      "@babel/plugin-transform-runtime"
    ]

複製代碼

polyfills.js 刪除babel-polyfill

//import 'babel-polyfill';
//import "core-js/modules/es6.promise";

複製代碼

總結

app.js 1.78M -> 125k 體積減少 90%

vendor.js 324k -> 208k 體積減少 35%

由以前的3個包 拆分打包成多個 ,按需加載。

速度篇

building modules chunk asset optimization

以前是 60s-70s 體積優化後穩定在 40-50s(穩定在45s左右) 提高速度 20% 左右

1.使用 webpack-parallel-uglify-plugin 插件來壓縮代碼

當 Webpack 有多個 JavaScript 文件須要輸出和壓縮時,本來會使用 UglifyJS 去一個個挨着壓縮再輸出, 可是 ParallelUglifyPlugin 則會開啓多個子進程,把對多個文件的壓縮工做分配給多個子進程去完成

const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');

 new ParallelUglifyPlugin({
                uglifyOptions: {
                    // 最緊湊的輸出
                    beautify: false,
                    // 刪除全部的註釋
                    comments: false,
                    compress: {
                        warnings: false, // 警告開關
                        drop_console: true,
                        // 內嵌定義了可是隻用到一次的變量
                        collapse_vars: true,
                        // 提取出出現屢次可是沒有定義成變量去引用的靜態值
                        reduce_vars: true
                    }
                },
                sourceMap: false,
                parallel: true , // 並行處理打包文件
                cache: true // 使用緩存

            })

複製代碼

[34.463, 38.368, 37.928, 36.127, 38.007] 平均 36.9786 36s 縮短 添加後穩定在 30-40s 大約10s

2.用 Happypack 來加速代碼構建

happypack把任務分解給多個子進程去併發的執行,子進程處理完後再把結果發送給主進程

new HappyPack({
            id: 'babel',
            loaders: [
                {
                    loader: 'babel-loader',
                    query: '?cacheDirectory',
                    options: {
                        presets: ['@babel/env']
                    }
                }],
            threadPool: happyThreadPool,
            verbose: true
        }),

複製代碼
{
            test: /\.js$/,
            include: [srcPath, iqiyiPath],
            exclude: /(node_modules|bower_components)/,
            loader: 'happypack/loader?id=babel'
        },

複製代碼

[35.357, 37.762, 44.798, 33.635, 33.427, 33.473, 32.468] 均值 35.845

new HappyPack({
            id: 'vue-loader',
            loaders: ['vue-loader'],
            threadPool: happyThreadPool,
            verbose: true
        })

複製代碼
{
            test: /\.vue$/,
            include: srcPath,
            loader: 'happypack/loader?id=vue-loader'
        },

複製代碼

[37.683, 39.648, 35.499, 35.108, 37.419, 35.862] 均值 36.869

new HappyPack({
            id: 'css-loader',
            loaders: ['css-loader'],
            threadPool: happyThreadPool,
            verbose: true
        })

複製代碼
{
            test: /\.css$/,
            use: [
                MiniCssExtractPlugin.loader,
                //'css-loader'
                'happypack/loader?id=css-loader'
            ]
        }

複製代碼

[ 39.394, 39.443, 35.080, 37.253 ,37.501, 35.632] 均值 37.383

[35.639, 36.382, 34.144, 33.420, 34.641, 32.504, 34.313] 34.434 速度穩定在30-35之間,縮短大約 1-2s

3.添加babel cacheDirectory

4.devtool

devtool: 'source-map' 構建速度: 25.133, 26.545, 25.956, 24.763, 26.953 ~ 25.869 從新構建速度: 1.387, 1.632 ,1.872, 1.809, 0.932 ~ 1.526

devtool 構建速度 從新構建速度 生產環境 品質(quality)
eval 21.473 +++ 0.6822 +++ no 生成後的代碼
cheap-eval-source-map 23.251 + 0.8622 ++ no 轉換過的代碼(僅限行)
cheap-module-eval-source-map 24.9536 o 1.124 ++ no 原始源代碼(僅限行)
eval-source-map 24.161 -- 0.9534 + no 原始源代碼

總結

最終打包速度從 60-70 下降到 30-35s 下降大約 20-25s 左右 提高速度大約 30% 左右 開發速度 二次打包速度 從 2.7~2.9s 左右下降到 0.6~0.9s,大約提速2s ,提速 60%-70% 左右 devtoo:eval

左右下降到 0.8~1.3s, 平均1.124,大約提速1s ,提速 35% 左右 devtoo:cheap-module-eval-source-map

相關文章
相關標籤/搜索