webpack 性能優化二

                         Webpack 性能優化(二)

一、使用DllPlugin(動態鏈接庫):將網頁依賴的基礎模塊比如rect,react-dom,vue模塊抽離出來,打包到一個個單獨的動態鏈接庫中,當業務需要的導入的模塊存在鏈接庫中,不會再次打包,而是直接去取,

Webpack插件:
DllPlugin: 用於打包出一個個單獨的動態鏈接庫文件
DllReferencePlugin: 用於在主要的配置文件中引入DllPlugin插件打包好的動態鏈接庫

const path = require(‘path’);
const DllPlugin = require(‘webpack/lib/DllPlugin’);

module.exportsc = {
entry: {
polyfill: [
‘core-js/fn/obejct/assign’,
‘core-js/fn/promise’,
‘whatwg-fetch’
]
},
output: {
path: path.join(__dirname, ‘dist’),
filename: ‘[name].dll.js’,
library: ‘dll[name]’
},
plugins: [
new DllPlugin({
name: ‘dll[name]’,
path: path.join(__dirname, ‘dis’, ‘[name].mainfest.json’)
})
]
}

plugin: [
new DllReferencePlugin({
manifest: require(’./dist/polyfill.mainfest.json’)
})
],
devtool: ‘sourse-map’

二、使用HappyPack(分解任務和管理線程)

將部分任務分解到多個進程中去並行處理
module: {
rules:[{
test: /.js$/,
//use: [‘babel-loader?cacheDirectory’],

        use: ['happypack/loader?id=label'],
        include: path.resolve(__dirname, 'src'),
        exclude: path.resolve(__dirname, 'node_modules')
    }, {
        test: /\.css$/,
        use: [
            MiniCssExtractPlugin.loader,
            'happyhack/loader?id=css'
        ]
    }]
},
plugin: [
    new DllReferencePlugin({
        manifest: require('./dist/polyfill.mainfest.json')
    }),
    new HappyPack({
        id: 'babel',
        loader:['babel-loader?cacheDirectory'],
        threadPool:  happyThreadPool
    }),
    new HappyPack({
        id: 'css',
        loader:['css-loader'],
        threadPool: happyThreadPool
    })
],
devtool: 'sourse-map'

三、ParalleUglifyPlugin 並行壓縮代碼

new ParallelUglifyPlugin({
uglifyJS: {
output: {
beautify: false, //緊湊輸出
comments: false //刪除註釋
}
}
})

四、使用自動刷新瀏覽器

1.自動刷新原理
(1)藉助瀏覽器提供的接口去刷新
(2)想要開發的網頁注入代理客戶端代碼,通過代理客戶端刷新這個頁面
(3)將要開發的網頁裝進iframe,通過刷新iframe看到最新效果

Web-dev-server默認採用的是第二種

Webpack-dev-server --inline false 採用第三種,不用給每個輸出的chunk都注入代理客戶端代碼

五、開啓模塊熱替換

 new ParallelUglifyPlugin({
        uglifyJS: {
            output: {
                beautify: false,    //緊湊輸出
                comments: false     //刪除註釋
            }
        }
    }),
    new HotModuleReplacementPlugin()
],
devServer:{
    hot: true
},

六、區分環境(壓縮代碼)

process.env.NODE_ENV

七、CDN加速(內容分發網絡,加速網絡傳輸)

publicPath: ‘’
Web-webpack-plugin

八、Tree Shaking(針對ES6)

關閉babel自動轉換功能,再通過壓縮UglifyJS處理或者直接運行的時候帶上 --optimize-minimize參數
{
“presets”: [
[
“env”,
{
“modules”: false
}
]
]
}

九、提取公共代碼—CommonChunkPlugbin

new HotModuleReplacementPluCommonChunkPlugbingin(),
new CommonChunkPlugbin({
chunks: [‘a’, ‘b’],
name: ‘common’
})

十、分割代碼按需加載(vue require)

十、Prepack(優化代碼在運行時的效率)

在編譯階段預執行源碼得到結果

new CommonChunkPlugbin({
chunks: [‘a’, ‘b’],
name: ‘common’
}),
new PrepackWebpackPlugin()

十一、Scope Hoisting(作用域提升, ES6)

打出來的文件更小,運行的更快

new PrepackWebpackPlugin(),
new ModuleConcatenationPlugin()

十二、可視化分析工具 webpack analyse webpack-bundle-analyzer

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章