自動生成html,基本用法:css
new HtmlWebpackPlugin({
filename: 'index.html', // 生成文件名
template: path.join(process.cwd(), './index.html') // 模班文件
})
複製代碼
拷貝資源插件html
基本用法:node
new CopyWebpackPlugin([
{
from: path.join(process.cwd(), './vendor/'),
to: path.join(process.cwd(), './dist/'),
ignore: ['*.json']
}
])
複製代碼
倆個插件效果一致,都是生成編譯結果的資源單,只是資源單的數據結構不一致而已。react
webpack-manifest-plugin 基本用法:jquery
module.exports = {
plugins: [
new ManifestPlugin()
]
}
複製代碼
assets-webpack-plugin 基本用法:webpack
module.exports = {
plugins: [
new AssetsPlugin()
]
}
複製代碼
在編譯以前清理指定目錄指定內容。git
基本用法:github
// 清理目錄
const pathsToClean = [
'dist',
'build'
]
// 清理參數
const cleanOptions = {
exclude: ['shared.js'], // 跳過文件
}
module.exports = {
// ...
plugins: [
new CleanWebpackPlugin(pathsToClean, cleanOptions)
]
}
複製代碼
提供帶 Content-Encoding 編碼的壓縮版的資源web
基本用法:json
module.exports = {
plugins: [
new CompressionPlugin()
]
}
複製代碼
編譯進度條插件
基本用法:
module.exports = {
//...
plugins: [
new ProgressBarPlugin()
]
}
複製代碼
自動加載模塊,如 $
出現,就會自動加載模塊;$
默認爲'jquery'的exports
用法:
new webpack.ProvidePlugin({
$: 'jquery',
})
複製代碼
定義全局常量
用法:
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
}
})
複製代碼
提取css樣式,對比:
基本用法 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文件名
})
]
}
複製代碼
忽略regExp匹配的模塊
用法:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
複製代碼
代碼醜化,用於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
}
}
}]
}
};
複製代碼
css壓縮,主要使用 cssnano 壓縮器
用法:
module.exports = {
//...
optimization: {
minimizer: [new OptimizeCssAssetsPlugin({
cssProcessor: require('cssnano'), // css 壓縮優化器
cssProcessorOptions: { discardComments: { removeAll: true } } // 去除全部註釋
})]
}
};
複製代碼
使你的chunk根據內容生成md5,用這個md5取代 webpack chunkhash。
var WebpackMd5Hash = require('webpack-md5-hash');
module.exports = {
// ...
output: {
//...
chunkFilename: "[chunkhash].[id].chunk.js"
},
plugins: [
new WebpackMd5Hash()
]
};
複製代碼
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
}
}
}
}
};
複製代碼
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'
]
}
})
]
}
複製代碼
多線程編譯,加快編譯速度,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"
]
}
]
}
}
複製代碼
使用模塊編譯緩存,加快編譯速度。
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')
}
]
}
}
複製代碼
編譯模塊分析插件
基本用法:
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'
}),
複製代碼
stats-webpack-plugin 將構建的統計信息寫入文件,該文件可在 webpack.github.io/analyse中上傳進行編譯分析,並根據分析結果,可以使用 PrefetchPlugin 對部分模塊進行預解析編譯(本人也不理解這個plugin,聽說優化效果不明顯,有興趣的同窗請見 how-to-optimize-webpacks-build-time-using-prefetchplugin-analyse-tool)。
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')
];
}
複製代碼
統計編譯過程當中,各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);
複製代碼