html Webpack Plogin

来源:互联网 发布:阿里云备案.top 编辑:程序博客网 时间:2024/06/03 17:04

    • HTML Webpack Plugin
    • Installation
    • Basic Usage
    • Configuration
    • Generating Multiple HTML Files
    • Writing Your Own Templates
    • 实例
    • 参考

HTML Webpack Plugin

This is a webpack plugin that simplifies creation of HTML files to serve your webpack bundles. This is especially useful for webpack bundles that include a hash in the filename which changes every compilation. You can either let the plugin generate an HTML file for you, supply your own template using lodash templates or use your own loader.

Maintainer: Jan Nicklas @jantimon

这个插件能够很好的处理HTML文件对webpack中的chunks依赖。有些依赖(某些js文件)在每一次编译的时候,文件名由于使用hash生成,每一次编译都不一样,使用这个插件可以解决HTML文件动态引入变化的文件名。所以,使用这个插件之后,可以很好的让HTML文件依赖于任何的webpack chunks。

Installation

使用npm/cnpm安装这个插件:

npminstallhtmlwebpackpluginsavedev cnpm install html-webpack-plugin –save-dev

Basic Usage

The plugin will generate an HTML5 file for you that includes all your webpack bundles in the body using script tags. Just add the plugin to your webpack config as follows:

这个插件将会形成一个 在body中使用script标签引入的所有webpack chunks 的HTML文件。仅仅是和下面这样在webpack.config.js文件中增加这个插件:

var HtmlWebpackPlugin = require('html-webpack-plugin');var webpackConfig = {  entry: 'index.js',  output: {    path: __dirname + '/dist',    filename: 'index_bundle.js'  },  plugins: [new HtmlWebpackPlugin()]};

This will generate a file dist/index.html containing the following:

这样,插件会 默认 在dist目录下生成一个index.html的文件,这个文件的内容中默认在body标签里面有对上述配置文件中管理的所有chunks引用。

<!DOCTYPE html><html>  <head>    <meta charset="UTF-8">    <title>Webpack App</title>  </head>  <body>    <script src="index_bundle.js"></script>  </body></html>

If you have multiple webpack entry points, they will all be included with script tags in the generated HTML.

由于webpack配置文件中只是生成了index_bundle.js文件,所以这个html文件就有对这个文件的引用,如果更多的文件那么将应用的更多,同时index.html的位置也是默认为上述配置文件中path指定的位置。文件名默认为index.html。

If you have any CSS assets in webpack’s output (for example, CSS extracted with the ExtractTextPlugin) then these will be included with tags in the HTML head.

如果你有css输出文件,那么他将通过link标签添加到生成的HTML head中。

(怎么解决将css js文件分开处理,防止出现在script中引用css文件)

总之:在配置文件中new一个HtmlWebpackPlugin就可以使用这个插件提供的服务,在没有参数默认的情况下,会在path下创建一个idnex.html文件,这个文件中有对配置文件中输出的chunks的引用,js通过script,css通过在head中link方式,这些应用的文件名字与生成的文件名一致。

Configuration

可以通过如下的参数操作HtmlWebpackPlugin对象的行为:

title:string
用于声明生成的HTML页面的document。

filename:URL
规定生成HTML文件的文件名。默认为 index.html。
你也可以指定一个相对地址。(比如:assets/admin.html )

template:URL
定义生成的HTML文件是根据哪一个定义好的HTML文件生成的。
在2.x版本中,引入的模板可以先经过loader处理后在使用。(还未验证)

inject:true|false
默认插入body,inject声明了引入的文件如何插入到html模板
中,当赋值为true或者”body”,所有的js引用将放入到body标签里面的底部,”head”将script标签放在head中。如果为false,可以通过下面介绍的使用
htmlWebpackPlugin.files参数自定义。

favicon:URL
增加网站图标(ico)的地址增加到html上

minify:{…} | false
根据对象内参数对输出页面进行压缩。包括 取消空白字符、注释等。
参数参考 如下:html-minifier;

hash:true | false
如果为true, 则添加一个唯一的hash值通过 ?[hash]方式
添加到引用的script和css文件地址的末尾。这总方式对于取消缓存是非常有用的。

cache:true | false
如果是true(默认值)则仅仅是发布变化的部分

showErrors:true | false
如果为true(默认值)错误细节将写入html页面中.

chunks:[]
添加这个生成的HTML页面以来的chunks.

chunksSortMode:’none’ | ‘auto’ | ‘dependency’ | {function} default: ‘auto’
在chunks加入到html页面之前,允许对chunks进行排序

excludeChunks:[]
使用从output中排除数组中声明的chunks,对output chunks求补集

xhtml:true | false Default is false
如果是true,link标签是自闭合的

一个实例:

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

Generating Multiple HTML Files

如果要生成多余一个的页面,那么就要在配置中定义多个数组:

{  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'    })  ]}

定义了两个页面,第一个页面默认名称为index.html保存在dist目录中,默认添加所有的output chunks引用。第二个页面也是位于dist目录下,如果想更改目录可以将filename
改为 page/test.html。 使用的模板是src/assets/test.html,也是默认将output chunks都应用那个到生成的html中。

Writing Your Own Templates

如果默认生成的html不能满足自身的需求的话,可以使用自己定义好的html模板对生成的html定义。最简单的方式使用template参数和一个html模板路径。这个插件将自动的生成一个 注入了依赖chunks的 根据模板html的 html页面。

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

my-index.ejs:

<!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-loader, 并且使用.html文件最为模板,那么加载器将会解析html模板到生成的html模板中。

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

如果使用inject注入引用的默认方式不满足我们的需求,想要控制明确使用引用在模板的位置,比如 有一部分在head中有一部分在body中。

在html模板中使用htmlWebpackPlugin 变量可以插件的具体的数据,htmlWebpackPlugin分为两个属性为files和options:分别介绍:

htmlWebpackPlugin.files:这个参数描述了这个html依赖的js文件和css 文件,同时也写出了每一个chunks入口文件。如果你设置一个publicPath在你的webpack配置文件中,那么将使用publicPath替代path

"htmlWebpackPlugin": {  "files": {    "publicPath":"../",    favicon:"favicon.ico",    "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": []      },    }  }}

htmlWebpackPlugin.options:这个参数可以查看该插件设置的一些参数的信息,比如tmplate、title、minify等。

webpack: the webpack stats object. Note that this is the stats object as it was at the time the HTML template was emitted and as such may not have the full set of stats that are available after the webpack run is complete.

webpackConfig: the webpack configuration that was used for this compilation. This can be used, for example, to get the publicPath (webpackConfig.output.publicPath).
webpackConfig:经过这个html模板生成之后的webpack配置信息。

实例:

生成一个html页面名字为maotr.html,位于dist/page
下,这个页面依赖于index.html模板,仅仅使用a,b chunks,并且a chunks位于head中, b chunks位于body中。生成的页面是经过压缩后的。

webpack.config.js:

var path = require("path");var htmlWebpcakPlugin = require("html-webpack-plugin");module.exports = {    entry: {        a: "./src/script/a.js",        b: "./src/script/b.js",        c: "./src/script/c.js",        main: "./src/script/main.js"    },    output: {        filename: "js/[name]-[chunkhash].js",        path: path.resolve(__dirname, 'dist'),        publicPath: "http://maotr.com"    },    plugins: [        new htmlWebpcakPlugin({            template: "./index.html",            filename: "page/maotr.html",            title: "maotr",            chunks: ["a", "b"],            minify: {                collapseWhitespace: true            },            inject: false        })    ]}

index.html:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">        <title><%= htmlWebpackPlugin.options.title%></title>        <script src="<%= htmlWebpackPlugin.files.chunks.a.entry%>"></script></head><body><script src="<%= htmlWebpackPlugin.files.chunks.b.entry %>"></script></head></body></html>

生成的maotr.html

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>maotr</title><script src="http://maotr.com/js/a-c867f70e8497eb071e4e.js"></script></head><body><script src="http://maotr.com/js/b-c4b4755ffcfaf15dfdf3.js"></script></body></html>

参考

https://github.com/jantimon/html-webpack-plugin

原创粉丝点击