webpack htmlWebpackPlugin 靜態資源 版本控制


    plugins: [
        new webpack.optimize.UglifyJsPlugin({   // 壓縮webpack 后生成的代碼較長時間,通常推到生產環境中才使用
            compress:{
                warnings: false
            }
        }),
        new htmlWebpackPlugin({   // webpack 指定目錄(package內設置)生成靜態HTML文件
            title: "自動生成網頁標題",
            filename: "test.html",
            template: "temIndex.html",
            hash: true,       // true | false。如果是true,會給所有包含的script和css添加一個唯一的webpack編譯hash值。這對於緩存清除非常有用。
            inject: true,     // | 'head' | 'body' | false  ,注入所有的資源到特定的 template 或者 templateContent 中,如果設置為 true 或者 body,所有的 javascript 資源將被放置到 body 元素的底部,'head' 將放置到 head 元素中。
            chunks: ["app"]   // 使用chunks 需要指定entry 入口文件中的哪一個模塊
        })
    ]

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'
    })
  ]
}
復制代碼

 

 

生成多個 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 
  })
]
復制代碼

 

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" }
  ]
},
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 '..';
    }
  })
]
復制代碼

 

或者異步版本

復制代碼
plugins: [
  new HtmlWebpackPlugin({
    templateContent: function(templateParams, compilation, callback) {
      // Return your template content asynchronously here 
      callback(null, '..');
    }
  })
]
復制代碼

 

注意,如果同時使用 template 和 templateContent ,插件會拋出錯誤。

變量 o 在模板中是在渲染時傳遞進來的數據,這個變量有如下的屬性:

  • 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": []
            },
          }
        }
      }
      復制代碼

       如果在 webpack 配置文件中,你配置了 publicPath,將會反射正確的資源

    • htmlWebpackPlugin.options: 傳遞給插件的配置。
  • webpack: webpack 的 stats 對象。
  • webpackConfig: webpack 配置信息。

過濾塊

可以使用 chunks 來限定特定的塊。

plugins: [
  new HtmlWebpackPlugin({
    chunks: ['app']
  })
]

 

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

plugins: [
  new HtmlWebpackPlugin({
    excludeChunks: ['dev-helper']
  })
]

 

事件

通過事件允許其它插件來擴展 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();
});

 

下面是一個在使用的webpack配置文件

————————————————————————————————————————————————

/**
 * Created by Administrator on 2016/8/14.
 */
var webpack = require("webpack")
var htmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
    entry: {
        app: "./lib/main.js"
    },
    output: {
        path: "./",
        filename: "bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.vue$/,
                exclude: /node_modules/,
                loader: 'vue'
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {
                    presets: ['es2015']   // babelrc 文件一定不要忘了
                }
            }
        ]
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({   // 壓縮webpack 后生成的代碼較長時間,通常推到生產環境中才使用
            compress:{
                warnings: false
            }
        }),
        new htmlWebpackPlugin({   // webpack 指定目錄(package內設置)生成靜態HTML文件
            title: "自動生成網頁標題",
            filename: "test.html",
            template: "temIndex.html",
            hash: true,       // true | false。如果是true,會給所有包含的script和css添加一個唯一的webpack編譯hash值。這對於緩存清除非常有用。
            inject: true,     // | 'head' | 'body' | false  ,注入所有的資源到特定的 template 或者 templateContent 中,如果設置為 true 或者 body,所有的 javascript 資源將被放置到 body 元素的底部,'head' 將放置到 head 元素中。
            chunks: ["app"]   // 使用chunks 需要指定entry 入口文件中的哪一個模塊
        })
    ]
}

.babelrc

{
  "presets": ["es2015","stage-0"],
  "plugins": ["transform-runtime"]
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM