zoukankan      html  css  js  c++  java
  • html-webpack-plugin

    简介:

       html-webpack-plugin 是一个webpack插件,它简化了注入webpack打包文件的html的创建。当webpack打包文件使用哈希值作为文件名并且每次编译的哈希值都不同时尤其有用。你可以使用lodash模板来创建html文件,也可以使用你自己的加载器。

    安装:

    npm install html-webpack-plugin --save-dev

    第三方插件:

        html-webpack-plugin 通过提供钩子(参考下面的事件)来扩展你的需求。可以通过零配置来集成下面这些非常有用的插件:

    基本用法:

        插件生成一个在 <body> 内使用 <script> 标签引入所有 webpack 打包文件的html5文件。

        像下面这样将插件添加到 webpack 配置文件中:

     1  var HtmlWebpackPlugin = require('html-webpack-plugin');
     2 
     3     var webpackConfig = {
     4 
     5         entry: 'index.js',
     6 
     7         output: {
     8 
     9             path: __dirname _ './dist',
    10 
    11             filename: 'index_bundle.js'
    12 
    13         },
    14 
    15         plugins: [new HtmlWebpackPlugin()]
    16 
    17     };

        这将会在项目根目录下的 dist 文件夹中生成一个包含如下内容的 index.html 文件:

     1 <!DOCTYPE html>
     2  <html>
     3    <head>
     4      <meta charset="UTF-8">
     5      <title>Webpack App</title>
     6    </head>
     7    <body>
     8      <script src="index_bundle.js"></script>
     9    </body>
    10  </html>

        如果有多个入口点,所有的打包文件都会被 <script> 标签引入到生成的html文件中。

        如果 webpack 输出了 CSS 资源(例如:使用 ExtractTextPlugin 产出的CSS文件),这些CSS文件会被 <link> 标签引入到html的 <head> 中。

    配置:

        你可以通过一个散列对象来配置 HtmlWebpackPlugin。可配置的属性如下:

    •     title: 设置生成的html文件的<title>值
    •     filename: 设置生成的html文件名,默认是 index.html 。你也可以在这设置子文件夹路径(例如: assets/admin.html)
    •     template: 设置模板加载器

            1. 不设置任何加载器

                默认(如果你不使用任何加载器)使用 fallback lodash loader:

    {
      plugins: [
        new HtmlWebpackPlugin({
          template: 'src/index.html'
        })
      ]
    }

                注意,使用 .html 扩展名可能会意外的出发其他加载器。

            2. 直接设置模板加载器

    new HtmlWebpackPlugin({
      // For details on `!!` see https://webpack.github.io/docs/loaders.html#loader-order
      template: '!!handlebars!src/index.hbs'
    })

            3. 使用 module.loders 设置加载器

    {
      module: {
        loaders: [
          {
            test: /.hbs$/,
            loader: 'handlebars-loader'
          },
        ]
      },
      plugins: [
        new HtmlWebpackPlugin({
          template: 'src/index.hbs'
        })
      ]
    }

                下面的例子中,webpack将对模板使用 html-loader。这将会压缩html,并且禁用 ejs 加载器。

    {
      module: {
        loaders: [
          {
            test: /.html$/,
            loader: 'html-loader'
          }],
      },
      plugins: [
        new HtmlWebpackPlugin({
          template: 'src/index.html'
        })
      ]
    }
    •     inject: true | 'head' | 'body' | false 

            将所有资源注入到 template 或 templateContent 中。 如果设置为 true 或 'body' 所有的javascript资源将会注入到body元素的底部。

            如果设置为 'head' 则会把javascript资源注入到head元素中。

    •     favicon: 设置将被添加到html中的图标路径。
    •     minify: {...} | false

            通过设置 html-minifier 属性来压缩生成的html。

    •     hash: true | false

            如果为true,会给html中所有的javascript和css文件添加一个唯一的哈希值。这对清除缓存非常有用。

    •     cache: true | false

            默认为true,只有当文件该变时才会触发编译

    •     showErrors: true | false

            默认为true,错误的详细信息将会被写入到html页面中。

    •     chunks: 设置允许添加的模块(例如: 只允许添加 unit-test 模块)
    •     chunksSortMode: 'none' | 'auto' | 'dependency' | 'manual' | {function}  默认为 'auto'

            设置模块添加到html中的顺序

    •     excludeChunks: 设置忽略某些模块(例如: 不添加 unit-test 模块)
    •     xhtml: true | false 

            默认为false,如果为true,将 <link> 标签渲染为自关闭,兼容 XHTML。

        下面是一个如何使用这些属性的 webpack 配置示例:

    {
      entry: 'index.js',
      output: {
        path: __dirname + '/dist',
        filename: 'index_bundle.js'
      },
      plugins: [
        new HtmlWebpackPlugin({
          title: 'My App',
          filename: 'assets/admin.html'
        })
      ]
    }

    生成多个html文件:

        如果需要生成多个html文件,只需要在插件数组中多次创建 HtmlWebpackPlugin 对象即可:

    {
      entry: 'index.js',
      output: {
        path: __dirname + '/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不能满足你的需求,你可以自己编写模板。最简单的方式是配置 template 选项并传递一个自定义的html文件。

        html-webpack-plugin会自动将所有必要的CSS,JS,manifest 和 favicon 文件注入到标记中。例如:

         webpack.config.js : 

    plugins: [
      new HtmlWebpackPlugin({
        title: 'Custom template',
        template: 'my-index.html', // Load a custom template (lodash by default see the FAQ for details)
      })
    ]

        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>

        如果你已经设置了一个加载器,你可以使用这个加载器来解析模板。

        请注意,如果您指定了html-loader并使用.html文件作为模板,也会发生这种情况。

    module: {
      loaders: [
        { test: /.hbs$/, loader: "handlebars" }
      ]
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: 'Custom template using Handlebars',
        template: 'my-index.hbs'
      })
    ]

        如果 inject 特性不能满足你的需求而且你想自主控制资源注入的位置,那么你可以使用 html-webpack-template 项目

        的默认模板(default template)作为起点来编写你自己的模板。

       

        你可以在模板中使用以下变量:

             htmlWebpackPlugin : 特定于此插件的数据

                 htmlWebpackPlugin.files : webpack 的 stats 对象的 assetsByChunkName 属性的窜改表示,包含了从入口点名称到包文件名的映射。例如: 

    "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 对象。注意,这个stats对象存在于HTML模板发出的时候,因此可能不包含webpack运行完成后的stats的全部信息。

             webpackConfig : 用于此编译的webpack配置。这可以用来获取 publicPath(例如:webpackConfig.output.publicPath)

    过滤模块:

        设置只包含指定的模块:

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

        通过设置 excludeChunks 选项,排除指定的模块:

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

    事件:

        通过执行下列事件来允许其他插件更改html:

        异步事件:

    •    html-webpack-plugin-before-html-generation
    •    html-webpack-plugin-before-html-processing
    •    html-webpack-plugin-alter-asset-tags
    •    html-webpack-plugin-after-html-processing
    •    html-webpack-plugin-after-emit

        同步事件:

    •    html-webpack-plugin-alter-chunks

        实现示例: html-webpack-harddisk-plugin

        用法示例:

    // MyPlugin.js
    function MyPlugin(options) {
      // Configure your plugin with options...
    }
    MyPlugin.prototype.apply = function(compiler) {
      // ...
      compiler.plugin('compilation', function(compilation) {
        console.log('The compiler is starting a new compilation...');
        compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, callback) {
          htmlPluginData.html += 'The magic footer';
          callback(null, htmlPluginData);
        });
      });
    };
    module.exports = MyPlugin;

        然后 webpack.config.js 中配置为:

    plugins: [
      new MyPlugin({options: ''})
    ]

        注意,回调必须通过htmlPluginData传递给其他插件,监听相同的html-webpack-plugin-before-html-processing事件。

    本文翻译自 html-webpack-plugin , 英语水平有限, 翻译不当之处, 敬请指正.

  • 相关阅读:
    JMS基本概念
    SSH项目整合
    SSH框架搭建问题总结
    web项目中classPath指的是哪里?
    web项目中配置文件的加载顺序
    分布式电商系统项目总结
    关于javaweb中图片的存储问题
    商品详情页面的显示
    利用solr实现商品的搜索功能
    SSM框架的搭建与测试
  • 原文地址:https://www.cnblogs.com/yingtoumao/p/7913625.html
Copyright © 2011-2022 走看看