一、HtmlWebpackPlugin使用:
npm install html-webpack-plugin --save-dev
解釋:這個插件是簡化創建生成html(h5)文件用的,如果你引入的文件帶有hash值的話,這個尤爲的有用,不需要手動去更改引入的文件名!
默認生成的是index.html,基本用法爲:
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpackConfig = {
entry: 'index.js',
output: {
path: 'dist',
filename: 'index_bundle.js'
},
plugins: [new HtmlWebpackPlugin()]
};
js通過script的標籤引入到body中!
如果你使用了ExtractTextPlugin來提取css,將通過link在head中引入!
一般配置:
title: 用於生成的HTML文檔的標題,也就是html,head中`<title>ceshi</title>`
filename: 生成的文件名,default index.html
template: 模版(填寫相對路徑,與配置文件的相對路徑,例如:'./index.html'
hash: 增加hash值,使每次生成的都是唯一的不重複的
二、ExtractTextWebpackPlugin 分離我們的樣式文件,例如css,sass,less
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"),
//輸出在根目錄上,也可以這樣寫css/styles.css
]
}
其中plugins中的參數配置有:(string/object) id: 插件實例的唯一標識,默認情況下是自動生成的,不建議設置
filename: 生成文件的名稱,可以包含[name], [id] and [contenthash]
allChunks:(bollean) 從所有附加塊中提取(默認情況下,它僅從初始塊中提取)
rules裏面的參數配置有:(loader | object) options.use :
{String}/{Array}/{Object} 使用的編譯loader options.fallback :
{String}/{Array}/{Object} 當css沒有被提取的時候,可以當作保守用 options.publicPath :
可以覆蓋output裏的publickPath
如果想生成多個css文件的話,可以這樣寫:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractCSS = new ExtractTextPlugin('css/[name]-one.css');
const extractLESS = new ExtractTextPlugin('css/[name]-two.css');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: extractCSS.extract([ 'css-loader', 'postcss-loader' ])
},
{
test: /\.less$/i,
use: extractLESS.extract([ 'css-loader', 'less-loader' ])
},
]
},
plugins: [
extractCSS, //兩個實例
extractLESS
]
};
三、DefinePlugin 定義變量
允許我們創建可在編譯時配置的全局常量,這對與需要靈活配置的項目而言非常的重要,舉個例子:
開發中我們需要devtool來查看redux樹中stroe中的變量,但是生產環境中不需要,那麼就可以這樣定義:
const nodeEnv = process.env.NODE_ENV || 'development';
const isPro = nodeEnv === 'production';
new webpack.DefinePlugin({
"__dev__": JSON.stringify(isPro)
})
那麼在開發環境中__dev__爲false,
打包的時候可以在CLI中輸入NODE_ENV=production 這樣__dev__就爲true;
四、ProvidePlugin 提供識別碼
通俗點講就是使用一些字符代替複雜的字符,例如我想用 $ 代表 jQuery, 那麼就可以使用這個插件,或着我想用 ‘av’ 代表 ‘./ateon/values’ 這個路徑,也可以使用這個插件。
基本用法:
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'av' : './ateon/values'
})
在模塊中使用, import lives from 'av' === import lives from './ateon/values'
五、clean-webpack-plugin 清除你的build目錄
基本用法:
const CleanWebpackPlugin = require('clean-webpack-plugin')
// webpack config
{
plugins: [
new CleanWebpackPlugin(paths [, {options}])
]
}
[, {options}]爲可選參數
`path` An [array] of string
options 參數
{
root: __dirname,默認根目錄,也就是你的package的路徑(絕對路徑)
verbose: true, 在控制檯console日誌
dry: false, 默認爲false,刪除所有的文件, 爲true時,模擬刪除,並不刪除文件
watch: false, 默認false, 爲true時刪除所有的編譯文件
exclude: [ 'files', 'to', 'ignore' ]
}
一般這一項我們都使用默認值,不去設置,只需要設置path就可以了!
總結,常用的就是這些了,後續還會在陸續的加入。。。其他相關插件!