外掛 html-webpack-plugin 的詳解
最近在學習webpack,接觸到的第一個外掛就是html-webpack-plugin,那麼今天就來詳解一下它的用法吧。
先來上一個例子:
var htmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
module.exports = {
entry: './src/script/main.js',
output: {
filename: 'js/bundle.js',
path: path.resolve(__dirname, 'dist')
} ,
plugins: [
new htmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: 'head'
})
]
}
配置屬性
title
生成html檔案的標題
filename
就是html檔案的檔名,預設是index.html
template
指定你生成的檔案所依賴哪一個html檔案模板,模板型別可以是html、jade、ejs等。但是要注意的是,如果想使用自定義的模板檔案的時候,你需要安裝對應的loader哦。
舉例子:
$ npm install jade-loader --save-dev
// webpack.config.js
...
loaders: {
...
{
test: /\.jade$/,
loader: 'jade'
}
}
plugins: [
new HtmlWebpackPlugin({
...
jade: 'path/to/yourfile.jade'
})
]
如果你設定的 title 和 filename於模板中發生了衝突,那麼以你的title 和 filename 的配置值為準。
inject
inject有四個值: true body head false
true 預設值,script標籤位於html檔案的 body 底部 body script標籤位於html檔案的 body 底部 head script標籤位於html檔案的 head中 false 不插入生成的js檔案,這個幾乎不會用到的
favicon
給你生成的html檔案生成一個 favicon ,值是一個路徑
plugins: [
new HtmlWebpackPlugin({
...
favicon: 'path/to/my_favicon.ico'
})
然後再生成的html中就有了一個 link 標籤
<link rel="shortcut icon" href="example.ico">
minify
使用minify會對生成的html檔案進行壓縮。預設是false。html-webpack-plugin內部集成了 html-minifier,因此,還可以對minify進行配置:(注意,雖然minify支援BooleanObject,但是不能直接這樣寫:minify: true , 這樣會報錯 ERROR in TypeError: Cannot use ‘in’ operator to search for ‘html5’ in true , 使用時候必須給定一個 { } 物件 )
...
plugins: [
new HtmlWebpackPlugin({
...
minify: {
removeAttributeQuotes: true // 移除屬性的引號
}
})
]
cache
預設是true的,表示內容變化的時候生成一個新的檔案。
showErrors
當webpack報錯的時候,會把錯誤資訊包裹再一個pre中,預設是true。
chunks
chunks主要用於多入口檔案,當你有多個入口檔案,那就回編譯後生成多個打包後的檔案,那麼chunks 就能選擇你要使用那些js檔案
entry: {
index: path.resolve(__dirname, './src/index.js'),
devor: path.resolve(__dirname, './src/devor.js'),
main: path.resolve(__dirname, './src/main.js')
}
plugins: [
new httpWebpackPlugin({
chunks: ['index','main']
})
]
那麼編譯後:
<script type=text/javascript src="index.js"></script>
<script type=text/javascript src="main.js"></script>
如果你沒有設定chunks選項,那麼預設是全部顯示
excludeChunks
排除掉一些js
excludeChunks: ['devor.js']
// 等價於上面的
xhtml
一個布林值,預設值是 false ,如果為 true ,則以相容 xhtml 的模式引用檔案。
chunksSortMode
script的順序,預設四個選項: none auto dependency {function}
‘dependency’ 不用說,按照不同檔案的依賴關係來排序。
‘auto’ 預設值,外掛的內建的排序方式,具體順序…
‘none’ 無序?
{function} 提供一個函式?