之前一直使用create-react-app
這個腳手架進行react
開發,後面由於一些自定義的配置,轉而使用webpack
搭建一套本身的腳手架。可是在使用webpack
打包以後發現,納尼?怎麼文件這麼大??? 因而研究了一下如何處理webpack
打包以後文件太大的狀況,簡單記錄下來。css
首先,經過指定環境,告訴webpack
咱們當前處於production
環境中,要按照production
的方式去打包。html
//指定環境,將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官方文檔, Devtool配置對比, webpack sourcemap 選項多種模式的一些解釋, https://webpack.github.io/docs/configuration.html#devtool 若是你的文件在打包以後忽然變成好幾M,那麼不用想,確定是由於source-map
的緣由。source-map
在開發階段確實很好用,調試起來很方便,可是在生產環境下就不必部署了。 建議在prod
環境下關閉source-map
。react
安裝webpack
插件extract-text-webpack-plugin
。 npm install extract-text-webpack-plugin --save-dev
。 使用方法:webpack
plugins:[
new ExtractTextPlugin('static/css/styles.[contenthash].css'),
]
複製代碼
這裏使用了contenthash
,webpack
會根據內容去生成hash
值。git
UglifyJSPlugin
壓縮。經過UglifyJSPlugin
能夠壓縮咱們的*.js
文件。 安裝方法: npm install uglifyjs-webpack-plugin --save-dev
。 用法: UglifyJSPlugin詳細用法github
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
文件進行提取,創建一個獨立的文件。這個文件包含一些共用模塊,瀏這樣覽器只在剛開始的時候加載一次,便緩存起來供後續使用。而不用每次訪問一個新界面時,再去加載一個更大的文件。web
entry:{
app:'./entry',
vendor:['react','other-lib'],
},
plugins:[
new Webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
}),
]
複製代碼
咱們使用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//只有壓縮率比這個值小的資源纔會被處理
})
]
複製代碼
壓縮結果: npm
添加插件html-webpack-plugin
安裝: npm install html-webpack-plugin --save-dev
用法:segmentfault
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'
}),
]
複製代碼