webpack常用外掛總結篇
自動生成 html
,基本用法:
new HtmlWebpackPlugin({ filename: 'index.html', // 生成檔名 template: path.join(process.cwd(), './index.html') // 模班檔案 })
1.2 copy-webpack-plugin
拷貝資源外掛
new CopyWebpackPlugin([ { from: path.join(process.cwd(), './vendor/'), to: path.join(process.cwd(), './dist/'), ignore: ['*.json'] } ])
1.3 webpack-manifest-plugin && assets-webpack-plugin
倆個外掛效果一致,都是生成編譯結果的資源單,只是資源單的資料結構不一致而已
webpack-manifest-plugin 基本用法
module.exports = { plugins: [ new ManifestPlugin() ] }
assets-webpack-plugin 基本用法
module.exports = { plugins: [ new AssetsPlugin() ] }
1.4 clean-webpack-plugin
在編譯之前清理指定目錄指定內容
// 清理目錄 const pathsToClean = [ 'dist', 'build' ] // 清理引數 const cleanOptions = { exclude:['shared.js'], // 跳過檔案 } module.exports = { // ... plugins: [ new CleanWebpackPlugin(pathsToClean, cleanOptions) ] }
1.5 compression-webpack-plugin
提供帶 Content-Encoding
編碼的壓縮版的資源
module.exports = { plugins: [ new CompressionPlugin() ] }
1.6 progress-bar-webpack-plugin
編譯進度條外掛
module.exports = { //... plugins: [ new ProgressBarPlugin() ] }
二、程式碼相關類
2.1 webpack.ProvidePlugin
自動載入模組,如 $
出現,就會自動載入模組; $
預設為 'jquery'
的 exports
new webpack.ProvidePlugin({ $: 'jquery', })
2.2 webpack.DefinePlugin
定義全域性常量
new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV) } })
2.3 mini-css-extract-plugin && extract-text-webpack-plugin
提取css樣式,對比
-
mini-css-extract-plugin
為webpack4
及以上提供的plugin
,支援css chunk
-
extract-text-webpack-plugin
只能在webpack3
及一下的版本使用,不支援css chunk
基本用法 extract-text-webpack-plugin
const ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { module: { rules: [ { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) } ] }, plugins: [ new ExtractTextPlugin("styles.css"), ] }
基本用法 mini-css-extract-plugin
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { module: { rules: [ { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: '/'// chunk publicPath } }, "css-loader" ] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: "[name].css", // 主檔名 chunkFilename: "[id].css"// chunk檔名 }) ] }
三、編譯結果優化類
3.1 wbepack.IgnorePlugin
忽略 regExp
匹配的模組
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
3.2 uglifyjs-webpack-plugin
程式碼醜化,用於js壓縮
module.exports = { //... optimization: { minimizer: [new UglifyJsPlugin({ cache: true,// 開啟快取 parallel: true, // 開啟多執行緒編譯 sourceMap: true,// 是否sourceMap uglifyOptions: {// 醜化引數 comments: false, warnings: false, compress: { unused: true, dead_code: true, collapse_vars: true, reduce_vars: true }, output: { comments: false } } }] } };
3.3 optimize-css-assets-webpack-plugin
css壓縮,主要使用 cssnano
壓縮器 ofollow,noindex">https://github.com/cssnano/cssnano
module.exports = { //... optimization: { minimizer: [new OptimizeCssAssetsPlugin({ cssProcessor: require('cssnano'),// css 壓縮優化器 cssProcessorOptions: { discardComments: { removeAll: true } } // 去除所有註釋 })] } };
3.4 webpack-md5-hash
使你的 chunk
根據內容生成 md5
,用這個 md5
取代 webpack chunkhash
。
var WebpackMd5Hash = require('webpack-md5-hash'); module.exports = { // ... output: { //... chunkFilename: "[chunkhash].[id].chunk.js" }, plugins: [ new WebpackMd5Hash() ] };
3.5 SplitChunksPlugin
-
CommonChunkPlugin
的後世,用於chunk
切割。
webpack
把 chunk
分為兩種型別,一種是初始載入 initial chunk
,另外一種是非同步載入 async chunk
,如果不配置 SplitChunksPlugin
, webpack
會在 production
的模式下自動開啟,預設情況下, webpack
會將 node_modules
下的所有模組定義為非同步載入模組,並分析你的 entry
、動態載入( import()
、 require.ensure
)模組,找出這些模組之間共用的 node_modules
下的模組,並將這些模組提取到單獨的 chunk
中,在需要的時候非同步載入到頁面當中,其中預設配置如下
module.exports = { //... optimization: { splitChunks: { chunks: 'async', // 非同步載入chunk minSize: 30000, maxSize: 0, minChunks: 1, maxAsyncRequests: 5, maxInitialRequests: 3, automaticNameDelimiter: '~', // 檔名中chunk分隔符 name: true, cacheGroups: { vendors: { test: /[\\/]node_modules[\\/]/,// priority: -10 }, default: { minChunks: 2,// 最小的共享chunk數 priority: -20, reuseExistingChunk: true } } } } };
四、編譯優化類
4.1 DllPlugin && DllReferencePlugin && autodll-webpack-plugin
-
dllPlugin
將模組預先編譯,DllReferencePlugin
將預先編譯好的模組關聯到當前編譯中,當webpack
解析到這些模組時,會直接使用預先編譯好的模組。 -
autodll-webpack-plugin
相當於dllPlugin
和DllReferencePlugin
的簡化版,其實本質也是使用dllPlugin && DllReferencePlugin
,它會在第一次編譯的時候將配置好的需要預先編譯的模組編譯在快取中,第二次編譯的時候,解析到這些模組就直接使用快取,而不是去編譯這些模組
dllPlugin 基本用法:
const output = { filename: '[name].js', library: '[name]_library', path: './vendor/' } module.exports = { entry: { vendor: ['react', 'react-dom']// 我們需要事先編譯的模組,用entry表示 }, output: output, plugins: [ new webpack.DllPlugin({// 使用dllPlugin path: path.join(output.path, `${output.filename}.json`), name: output.library // 全域性變數名, 也就是 window 下 的 [output.library] }) ] }
DllReferencePlugin 基本用法:
const manifest = path.resolve(process.cwd(), 'vendor', 'vendor.js.json') module.exports = { plugins: [ new webpack.DllReferencePlugin({ manifest: require(manifest), // 引進dllPlugin編譯的json檔案 name: 'vendor_library' // 全域性變數名,與dllPlugin宣告的一致 } ] }
autodll-webpack-plugin 基本用法:
module.exports = { plugins: [ new AutoDllPlugin({ inject: true, // 與 html-webpack-plugin 結合使用,注入html中 filename: '[name].js', entry: { vendor: [ 'react', 'react-dom' ] } }) ] }
4.2 happypack && thread-loader
多執行緒編譯,加快編譯速度, thread-loader
不可以和 mini-css-extract-plugin
結合使用
happypack 基本用法
const HappyPack = require('happypack'); const os = require('os'); const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length }); const happyLoaderId = 'happypack-for-react-babel-loader'; module.exports = { module: { rules: [{ test: /\.jsx?$/, loader: 'happypack/loader', query: { id: happyLoaderId }, include: [path.resolve(process.cwd(), 'src')] }] }, plugins: [new HappyPack({ id: happyLoaderId, threadPool: happyThreadPool, loaders: ['babel-loader'] })] }
thread-loader 基本用法
module.exports = { module: { rules: [ { test: /\.js$/, include: path.resolve("src"), use: [ "thread-loader", // your expensive loader (e.g babel-loader) "babel-loader" ] } ] } }
4.3 hard-source-webpack-plugin && cache-loader
使用模組編譯快取,加快編譯速度
hard-source-webpack-plugin 基本用法
module.exports = { plugins: [ new HardSourceWebpackPlugin() ] }
cache-loader 基本用法
module.exports = { module: { rules: [ { test: /\.ext$/, use: [ 'cache-loader', ...loaders ], include: path.resolve('src') } ] } }
五、編譯分析類
5.1 webpack-bundle-analyzer
編譯模組分析外掛
new BundleAnalyzerPlugin({ analyzerMode: 'server', analyzerHost: '127.0.0.1', analyzerPort: 8889, reportFilename: 'report.html', defaultSizes: 'parsed', generateStatsFile: false, statsFilename: 'stats.json', statsOptions: null, logLevel: 'info' }),
5.2 stats-webpack-plugin && PrefetchPlugin
stats-webpack-plugin
將構建的統計資訊寫入檔案,該檔案可在 http://webpack.github.io/analyse中上傳進行編譯分析,並根據分析結果,可使用 PrefetchPlugin
對部分模組進行預解析編譯
stats-webpack-plugin 基本用法:
module.exports = { plugins: [ new StatsPlugin('stats.json', { chunkModules: true, exclude: [/node_modules[\\\/]react/] }) ] };
PrefetchPlugin 基本用法:
module.exports = { plugins: [ new webpack.PrefetchPlugin('/web/', 'app/modules/HeaderNav.jsx'), new webpack.PrefetchPlugin('/web/', 'app/pages/FrontPage.jsx') ]; }
5.3 speed-measure-webpack-plugin
統計編譯過程中,各 loader
和 plugin
使用的時間
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin"); const smp = new SpeedMeasurePlugin(); const webpackConfig = { plugins: [ new MyPlugin(), new MyOtherPlugin() ] } module.exports = smp.wrap(webpackConfig);