webpack 自动生成 html 模板文件

概述

通过 html-webpack-plugin 插件,可以自动生成 html 文件到 output.path 目录,并将 webpack输出的 bundle 文件自动插入到 html 文件中。

安装

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

使用

入门使用

1
2
3
4
5
6
7
8
9
10
11
12
13
//1、引入 html-webpack-plugin
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
entry: 'index.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index_bundle.js'
},
// 2、在 plugins 中创建插件实例
plugins: [new HtmlWebpackPlugin()]
};

上面两个步骤会自动在 dist 目录生成 index.html 文件,并将 webpack 生成的 bundle.js 插入到 index.hml 中,如下:

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Webpack App</title>
<meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body>
<script src="main.js"></script></body>
</html>

实际使用

在实际工作场景中,我们很少使用 html-webpack-plugin 默认的 html 模板文件,为了使生成的 html 文件中的内容更符合项目的需要,通常会重新生成一份 html 文件,然后通过插件参数 template 配置成插件使用的 html 模板。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//1、引入 html-webpack-plugin
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
entry: 'index.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index_bundle.js'
},
// 2、在 plugins 中创建插件实例
plugins: [
// 3、通过给 HtmlWebpackPlugin 传递对象来配置参数
new HtmlWebpackPlugin({
filenmame: "index.html",// 配置输出 html 的名称
template: "./tpl.html",//配置模板 html 路径
}),
]

};

上面例子只使用了插件的部分功能,更多功能可以在 https://www.npmjs.com/package/html-webpack-plugin 进行查看。