vue-cli全家套相信很多人都用過,但可能很多人不太清楚webpack為解決打包文件過大做了哪些事情,今天我們就主要來聊聊這個。
首先配置全局變量
首先,通過指定環境,告訴webpack我們當前處于production環境中,要按照production的方式去打包。
//指定環境,將process.env.NODE_ENV環境與library關聯
new Webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
})
優化devtool中的source-map.
dev-tool提供了很多種選項,用來增強我們debug的能力,我們熟知的有:source-map,inline-source-map,cheap-source-map等等。詳細的用法可以參考 Devtool官方文檔(https://webpack.github.io/docs/configuration.html#devtool )。如果你的文件在打包之后突然變成好幾M,那么不用想,肯定是因為source-map的原因。source-map在開發階段確實很好用,調試起來很方便,但是在生產環境下就沒必要部署了。 建議在prod環境下關閉source-map。
剝離css文件,單獨打包
安裝webpack插件extract-text-webpack-plugin。
npm install extract-text-webpack-plugin --save-dev。
//使用方法:
plugins:[
new ExtractTextPlugin('static/css/styles.[contenthash].css'),
]
這里使用了contenthash,webpack會根據內容去生成hash值。
使用UglifyJSPlugin壓縮。
通過UglifyJSPlugin可以壓縮我們的*.js文件。
//安裝方法:
npm install uglifyjs-webpack-plugin --save-dev。
//使用方法
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
plugins: [
new UglifyJSPlugin({
parallel: 4,
uglifyOptions: {
output: {
comments: false,
beautify: false,
},
compress: {
warnings: false
},
},
cache: true,
}),
]
}
提取公共依賴
使用CommonsChunkPlugin插件,將多個js文件進行提取,建立一個獨立的文件。這個文件包含一些共用模塊,瀏這樣覽器只在剛開始的時候加載一次,便緩存起來供后續使用。而不用每次訪問一個新界面時,再去加載一個更大的文件。
entry:{
App:'./entry',
vendor:['react','other-lib'],
},
plugins:[
new Webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
}),
]
開啟gzip壓縮
我們使用compression-webpack-plugin插件進行壓縮。 安裝:npm install compression-webpack-plugin --save-dev。 compression-webpack-plugin 詳細用法 使用:
const CompressionPlugin = require("compression-webpack-plugin");
plugins:[
new CompressionPlugin({
asset: '[path].gz[query]', //目標資源名稱。[file] 會被替換成原資源。[path] 會被替換成原資源路徑,[query] 替換成原查詢字符串
algorithm: 'gzip',//算法
test: new RegExp(
'\.(js|css)$' //壓縮 js 與 css
),
threshold: 10240,//只處理比這個值大的資源。按字節計算
minRatio: 0.8//只有壓縮率比這個值小的資源才會被處理
})
]
壓縮結果:
開啟html壓縮,自動添加上面生成的靜態資源
添加插件html-webpack-plugin。
//安裝:
npm install html-webpack-plugin --save-dev
//使用方法:
plugins:[
new HtmlWebpackPlugin({
title: '',
template: __dirname + '/../public/index.html',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
chunksSortMode:'dependency'
}),
]






