要想讓webpack為我所用相叁,不僅要求我們在loader使用上得心應手群叶,更離不開對plugins的熟練使用。
如果說把webpack比喻成一臺豆?jié){機钝荡,我們需要一杯豆?jié){喝街立,我們要:
- 準備好原材料,好比我們的 entry 入口起點的處理埠通;
- 選擇豆?jié){品種赎离,好比我們在選擇 loader 加載器;
- 攪拌電機工作端辱,好比我們 plugins 插件的大用處梁剔;
- 完成倒出品嘗,好比我們 output 輸出文件的處理舞蔽;
- 電力保障在線荣病,好比我們 devServer 服務開啟。
這一形象的比喻渗柿,目的在于幫助我們理解webpack的工作機制个盆,要想用好它脖岛,就必須清楚每個module的原理和使用方法。
下面重點談談plugins的大用處:
插件(plugins)
loader 僅在每個文件的基礎上執(zhí)行轉換颊亮,而 插件(plugins) 更常用于(但不限于)在打包模塊的 “compilation” 和 “chunk” 生命周期執(zhí)行操作和自定義功能柴梆。webpack 的插件系統(tǒng)極其強大和可定制化。
- 使用方法:
想要使用一個插件终惑,你只需要 require() 它绍在,然后把它添加到 plugins 數(shù)組中。
多數(shù)插件可以通過選項(option)自定義雹有。你也可以在一個配置文件中因為不同目的而多次使用同一個插件偿渡,這時需要通過使用 new 來創(chuàng)建它的一個實例。
在webpack.config.js配置如下:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
const config = {
//入口配置
entry: './path/to/my/entry/file.js',
//輸出配置
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'my-first-webpack.bundle.js'
},
//模塊loader加載轉換
module: {
rules: [
{ test: /\.txt$/, use: 'raw-loader' }
]
},
//插件調用完成功能定制
plugins: [
//壓縮js插件
new webpack.optimize.UglifyJsPlugin(),
//以index.html文件為模板生成html5新文件
new HtmlWebpackPlugin({template: './src/index.html'})
]
};
module.exports = config;
常用webpack插件舉例
webpack 有著豐富的插件接口(rich plugin interface)霸奕。webpack 自身的多數(shù)功能都使用這個插件接口溜宽。這個插件接口使 webpack 變得極其靈活。
更多插件使用還請移步官網(wǎng)铅祸。
- CommonsChunkPlugin
The CommonsChunkPlugin is an opt-in feature that creates a separate file (known as a chunk), consisting of common modules shared between multiple entry points. By separating common modules from bundles, the resulting chunked file can be loaded once initially, and stored in cache for later use. This results in pagespeed optimizations as the browser can quickly serve the shared code from cache, rather than being forced to load a larger bundle whenever a new page is visited.
大致翻譯過來就是這個插件可以幫助你從眾多模塊中抽離并合并出一個公共模塊文件坑质,瀏覽器只加載一次即可,給頁面加載帶來速度上的提升临梗。
** 注意: 此插件屬于webpack內置 無需安裝 **
使用方法:
new webpack.optimize.CommonsChunkPlugin(options)
配置:
{
name: string, // or
names: string[],
// 這是 common chunk 的名稱涡扼。已經存在的 chunk 可以通過傳入一個已存在的 chunk 名稱而被選擇。
// 如果一個字符串數(shù)組被傳入盟庞,這相當于插件針對每個 chunk 名被多次調用
filename: string,
// common chunk 的文件名模板吃沪。可以包含與 `output.filename` 相同的占位符什猖。
minChunks: number|Infinity|function(module, count) -> boolean,
// 在傳入 公共chunk(commons chunk) 之前所需要包含的最少數(shù)量的 chunks 票彪。
// 數(shù)量必須大于等于2,或者少于等于 chunks的數(shù)量
chunks: string[],
// 通過 chunk name 去選擇 chunks 的來源不狮。chunk 必須是 公共chunk 的子模塊降铸。
// 如果被忽略,所有的摇零,所有的 入口chunk (entry chunk) 都會被選擇推掸。
children: boolean,
// 如果設置為 `true`,所有 公共chunk 的子模塊都會被選擇
deepChildren: boolean,
// If `true` all descendants of the commons chunk are selected
async: boolean|string,
// 如果設置為 `true`驻仅,一個異步的 公共chunk 會作為 `options.name` 的子模塊谅畅,和 `options.chunks` 的兄弟模塊被創(chuàng)建。
minSize: number,
// 在 公共chunk 被創(chuàng)建立之前噪服,所有 公共模塊 (common module) 的最少大小毡泻。
}
舉例:
// 提取公共文件
new webpack.optimize.CommonsChunkPlugin({
name: 'reset',
filename: 'vendor/common.js',
//(模塊必須被3個 入口chunk 共享)
minChunks: 3
}),
- ExtractTextWebpackPlugin
Extract text from a bundle, or bundles, into a separate file.
這個插件是用來分離的,出單獨的一個文件
安裝:
npm install --save-dev 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"),
]
}
它會將所有的入口 chunk(entry chunks)中引用的 *.css粘优,移動到獨立分離的 CSS 文件仇味。因此呻顽,你的樣式將不再內嵌到 JS bundle 中,而是會放到一個單獨的 CSS 文件(即 styles.css)當中邪铲。
- HotModuleReplacementPlugin
模塊熱替換插件,啟用熱替換模塊(Hot Module Replacement)芬位,也被稱為 HMR无拗。
注意:永遠不要在生產環(huán)境(production)下啟用 HMR
用法:
啟用 HMR 非常簡單带到,在大多數(shù)情況下也不需要設置選項。
new webpack.HotModuleReplacementPlugin({
// Options...
})
- HtmlWebpackPlugin
它簡化了HTML文件的創(chuàng)建英染,以便為您的webpack包提供服務揽惹。 這對于在文件名中包含每次會隨著變異會發(fā)生變化的哈希的webpack bundle尤其有用。
安裝
npm install --save-dev html-webpack-plugin
使用方法:
SPA單頁面時:
const HtmlWebpackPlugin = require('html-webpack-plugin');
var webpackConfig = {
entry: 'index.js',
output: {
path: 'dist',
filename: 'index_bundle.js'
},
plugins: [new HtmlWebpackPlugin()]
};
module.exports = webpackConfig;
這將會產生一個包含以下內容的文件 dist/index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>webpack App</title>
</head>
<body>
<script src="index_bundle.js"></script>
</body>
</html>
多頁面時:
{
entry: 'index.js',
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin(), // Generates default index.html
new HtmlWebpackPlugin({ // Also generate a test.html
filename: 'test.html',
template: 'src/assets/test.html'
})
]
}
- ProvidePlugin
自動加載模塊四康,而不必到處 import 或 require 搪搏。
當我們的應用大量使用jQuery或Zepto時,可以借助此插件實現(xiàn)一次認定闪金,到處使用疯溺。
注意:webpack內置,不用安裝
要自動加載 jquery哎垦,我們可以將兩個變量都指向對應的 node 模塊:
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
使用:Lodash Map
new webpack.ProvidePlugin({
_map: ['lodash', 'map']
})
- UglifyjsWebpackPlugin
to minify your JavaScript
這個插件用來壓縮你的js的囱嫩,uglify翻譯過來是丑化,弄的難看漏设,就是要變成在一堆的代碼墨闲,從而減小代碼文件的體積。
安裝:
npm i -D uglifyjs-webpack-plugin
使用方法:
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
plugins: [
new UglifyJSPlugin()
]
}
配置項:
{
parse: {
// parse options
},
compress: {
// compress options
},
mangle: {
// mangle options
properties: {
// mangle property options
}
},
output: {
// output options
},
sourceMap: {
// source map options
},
ecma: 5, // specify one of: 5, 6, 7 or 8
nameCache: null, // or specify a name cache object
toplevel: false,
ie8: false,
warnings: false,
}
更多參數(shù)請參考Uglifyjs官網(wǎng)