webpack打包優化
阿新 • • 發佈:2018-12-13
1.減小檔案搜尋範圍
配置resolve.modules
Webpack的resolve.modules配置模組庫(即 node_modules)所在的位置,在 js 裡出現 import ‘vue’ 這樣不是相對、也不是絕對路徑的寫法時,會去 node_modules 目錄下找。但是預設的配置,會採用向上遞迴搜尋的方式去尋找,但通常專案目錄裡只有一個node_modules,且是在專案根目錄,為了減少搜尋範圍,可以直接寫明 node_modules 的全路徑;同樣,對於別名(`alias)的配置,亦當如此:
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
resolve: {
extensions: ['.js', '.vue', '.json'],
modules: [
resolve('src'),
resolve('node_modules')
],
alias: {
'vue$': 'vue/dist/vue.common.js',
'src': resolve('src'),
'assets': resolve('src/assets') ,
'components': resolve('src/components'),
// ...
'store': resolve('src/store')
}
},
...
}
2.loader配置
宣告exclude
或include
欄位
-
exclude 排除不滿足條件的資料夾
-
include 需要被loader 處理的檔案或資料夾
{
test: /\.js$/,
loader: 'babel-loader',
// exclude: /node_modules/
include: [resolve ('src'), resolve('test'), resolve('static')]
}
3.替換程式碼壓縮工具
Webpack 預設提供的 UglifyJS 外掛,由於採用單執行緒壓縮,速度慢 ;
webpack-parallel-uglify-plugin 外掛可以並行執行 UglifyJS 外掛,更加充分而合理的使用 CPU 資源,這可以大大減少的構建時間;
當然,該外掛應用於生產環境而非開發環境,安裝外掛後,進行如下配置:
// 刪掉webpack提供的UglifyJS外掛
// new webpack.optimize.UglifyJsPlugin({
// compress: {
// warnings: false,
// drop_console: true
// },
// sourceMap: true
// }),
// 增加 webpack-parallel-uglify-plugin來替換
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
new ParallelUglifyPlugin({
cacheDir: '.cache/', // 設定快取路徑,不改動的呼叫快取,第二次及後面build時提速
uglifyJS:{
output: {
comments: false
},
compress: {
warnings: false
}
}
})
4.拷貝靜態檔案
使用copy-webpack-plugin外掛:把指定資料夾下的檔案複製到指定的目錄;其配置如下:
var CopyWebpackPlugin = require('copy-webpack-plugin')
plugins: [
...
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
5.關掉productionSourceMap
在config目錄下面的index.js檔案中,vue-cli腳手架對開發環境和生產環境都做了相關配置,其中在build配置下設定productionSourceMap為false,避免產出.map字尾結尾的js檔案,(除非需要線上除錯)