插件 html-webpack-plugin 的詳解

最近在學習webpack,接觸到的第一個插件就是html-webpack-plugin,那麼今天就來詳解一下它的用法吧。javascript

  • 先來上一個例子:
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'
        })
    ]
}

配置屬性

titlehtml

生成html文件的標題html5

filenamejava

就是html文件的文件名,默認是index.htmlwebpack

templateweb

指定你生成的文件所依賴哪個html文件模板,模板類型能夠是html、jade、ejs等。可是要注意的是,若是想使用自定義的模板文件的時候,你須要安裝對應的loader哦。npm

舉例子:函數

$ npm install jade-loader --save-dev
// webpack.config.js
...
loaders: {
    ...
    {
        test: /\.jade$/,
        loader: 'jade'
    }
}
plugins: [
    new HtmlWebpackPlugin({
        ...
        jade: 'path/to/yourfile.jade'
    })
]

若是你設置的 titlefilename於模板中發生了衝突,那麼以你的titlefilename 的配置值爲準。學習

injectui

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} 提供一個函數?

相關文章
相關標籤/搜索