深入解析webpack 外掛html-webpack-plugin

前端攻城小牛啊發表於2018-11-27

這個外掛用來簡化建立服務於 webpack bundle 的 HTML 檔案,尤其是對於在檔名中包含了 hash 值,而這個值在每次編譯的時候都發生變化的情況。你既可以讓這個外掛來幫助你自動生成 HTML 檔案,也可以使用 lodash 模板載入生成的 bundles,或者自己載入這些 bundles。

深入解析webpack 外掛html-webpack-plugin

Installation 使用 npm 安裝這個外掛

$ npm install html-webpack-plugin@2 --save-dev
複製程式碼

Basic Usage 這個外掛可以幫助生成 HTML 檔案,在 body 元素中,使用 script 來包含所有你的 webpack bundles,只需要在你的 webpack 配置檔案中如下配置:

var HtmlWebpackPlugin = require('html-webpack-plugin')
var webpackConfig = {
 entry: 'index.js',
 output: {
  path: 'dist',
  filename: 'index_bundle.js'
 },
 plugins: [new HtmlWebpackPlugin()]
}
複製程式碼

這將會自動在 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>
複製程式碼

如果你有多個 webpack 入口點,它們都會被包含在生成的 script 元素中。 如果有任何的 CSS 資源包含在 webpack 輸出中(例如,使用 ExtractTextPlugin 提煉出的 css ),這些將會使用 link 包含在 HTML 頁面的 head 元素中。 Configuration 可以進行一系列的配置,支援如下的配置資訊

  • title: 用來生成頁面的 title 元素
  • filename: 輸出的 HTML 檔名,預設是 index.html, 也可以直接配置帶有子目錄。
  • template: 模板檔案路徑,支援載入器,比如 html!./index.html
  • inject: true | 'head' | 'body' | false ,注入所有的資源到特定的 template 或者 templateContent 中,* * 如果設定為 true 或者 body,所有的 javascript 資源將被放置到 body 元素的底部,'head' 將放置到 head 元素中。
  • favicon: 新增特定的 favicon 路徑到輸出的 HTML 檔案中。
  • minify: {} | false , 傳遞 html-minifier 選項給 minify 輸出
  • hash: true | false, 如果為 true, 將新增一個唯一的 webpack 編譯 hash 到所有包含的指令碼和 CSS 檔案,對於解除 cache 很有用。
  • cache: true | false,如果為 true, 這是預設值,僅僅在檔案修改之後才會釋出檔案。
  • showErrors: true | false, 如果為 true, 這是預設值,錯誤資訊會寫入到 HTML 頁面中
  • chunks: 允許只新增某些塊 (比如,僅僅 unit test 塊)
  • chunksSortMode: 允許控制塊在新增到頁面之前的排序方式,支援的值:'none' | 'default' | {function}-default:'auto'
  • excludeChunks: 允許跳過某些塊,(比如,跳過單元測試的塊)

下面的示例演示瞭如何使用這些配置。

{
 entry: 'index.js',
 output: {
  path: 'dist',
  filename: 'index_bundle.js',
  hash: true
 },
 plugins: [
  new HtmlWebpackPlugin({
   title: 'My App',
   filename: 'assets/admin.html'
  })
 ]
}//歡迎加入全棧開發交流圈一起學習交流:864305860
複製程式碼

生成多個 HTML 檔案 通過在配置檔案中新增多次這個外掛,來生成多個 HTML 檔案。

{
 entry: 'index.js',
 output: {
  path: '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'
  })
 ]
}
複製程式碼

編寫自定義模板 如果預設生成的 HTML 檔案不適合你的需要看,可以建立自己定義的模板。方便的方式是通過 inject 選項,然後傳遞給定製的 HTML 檔案。html-webpack-plugin 將會自動注入所有需要的 CSS, js, manifest 和 favicon 檔案到標記中。

plugins: [
 new HtmlWebpackPlugin({
  title: 'Custom template',
  template: 'my-index.html', // Load a custom template 
  inject: 'body' // Inject all scripts into the body 
 })//歡迎加入全棧開發交流圈一起學習交流:864305860
]
複製程式碼

my-index.html 檔案

<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
  <title><%= htmlWebpackPlugin.options.title %></title>
 </head>
 <body>
 </body>
</html>
複製程式碼

如果你有模板載入器,可以使用它來解析這個模板。

module: {
 loaders: [
  { test: /\.hbs$/, loader: "handlebars" }
 ]//歡迎加入全棧開發交流圈一起學習交流:864305860
},
plugins: [
 new HtmlWebpackPlugin({
  title: 'Custom template using Handlebars',
  template: 'my-index.hbs',
  inject: 'body'
 })
]
複製程式碼

另外,如果你的模式是一個字串,可以使用 templateContent 傳遞它。

plugins: [
 new HtmlWebpackPlugin({
  inject: true,
  templateContent: templateContentString
 })
]
複製程式碼

如果 inject 特性不適合你的需要,你希望完全控制資源放置。 可以直接使用 lodash 語法,使用 default template 作為起點建立自己的模板。 templateContent 選項也可以是一個函式,以便使用其它語言,比如 jade:

plugins: [
 new HtmlWebpackPlugin({
  templateContent: function(templateParams, compilation) {
   // Return your template content synchronously here 
   return '..';
  }//歡迎加入全棧開發交流圈一起學習交流:864305860
 })
]
複製程式碼

或者非同步版本

plugins: [
 new HtmlWebpackPlugin({
  templateContent: function(templateParams, compilation, callback) {
   // Return your template content asynchronously here 
   callback(null, '..');
  }//歡迎加入全棧開發交流圈一起學習交流:864305860
 })
]
複製程式碼

注意,如果同時使用 template 和 templateContent ,外掛會丟擲錯誤。 變數 o 在模板中是在渲染時傳遞進來的資料,這個變數有如下的屬性: 1、htmlWebpackPlugin: 這個外掛的相關資料 ◦ htmlWebpackPlugin.files: 資源的塊名,來自 webpack 的 stats 物件,包含來自 entry 的從 entry point name 到 bundle 檔名對映。

"htmlWebpackPlugin": {
 "files": {
  "css": [ "main.css" ],
  "js": [ "assets/head_bundle.js", "assets/main_bundle.js"],
  "chunks": {
   "head": {
    "entry": "assets/head_bundle.js",
    "css": [ "main.css" ]
   },
   "main": {
    "entry": "assets/main_bundle.js",
    "css": []
   },//歡迎加入全棧開發交流圈一起學習交流:864305860
  }
 }
}
複製程式碼

如果在 webpack 配置檔案中,你配置了 publicPath,將會反射正確的資源 htmlWebpackPlugin.options: 傳遞給外掛的配置。 2、webpack: webpack 的 stats 物件。 3、webpackConfig: webpack 配置資訊。 過濾塊 可以使用 chunks 來限定特定的塊。

plugins: [
 new HtmlWebpackPlugin({
  chunks: ['app']
 })//歡迎加入全棧開發交流圈一起學習交流:864305860
]
複製程式碼

還可以使用 excludeChunks 來排除特定塊。

plugins: [
 new HtmlWebpackPlugin({
  excludeChunks: ['dev-helper']
 })//歡迎加入全棧開發交流圈一起學習交流:864305860
]
複製程式碼

事件 通過事件允許其它外掛來擴充套件 HTML。

  • html-webpack-plugin-before-html-processing
  • html-webpack-plugin-after-html-processing
  • html-webpack-plugin-after-emit

使用方式:

compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, callback) {
 htmlPluginData.html += 'The magic footer';
 callback();
});
複製程式碼

結語

感謝您的觀看,如有不足之處,歡迎批評指正。

本次給大家推薦一個免費的學習群,裡面概括移動應用網站開發,css,html,webpack,vue node angular以及面試資源等。 對web開發技術感興趣的同學,歡迎加入Q群:864305860,不管你是小白還是大牛我都歡迎,還有大牛整理的一套高效率學習路線和教程與您免費分享,同時每天更新視訊資料。 最後,祝大家早日學有所成,拿到滿意offer,快速升職加薪,走上人生巔峰。

相關文章