初识 html-webpack-plugin

新建一个文件夹

yarn init 初始化一下

yarn add webpack

使用

编写 webpack.config.js文件

1
2
3
4
5
6
7
8
9
10
11
12
13
const path = require(‘path’)
const HtmlWebpackPlugin = require(‘html-webpack-plugin’)

module.exports = {
entry: path.resolve(__dirname, ‘index.js’),
output: {
path: path.resolve(__dirname, ‘dist’),
filename: ‘index.js’
},
plugins: [
new HtmlWebpackPlugin()
]
}

config 里用到了 html-webpack-plugin ,所以别忘了 yarn add html-webpack-plugin

config 作用很明确,就是把 entry 输出到 output 配置的位置

plugins里,我们添加了一个 HtmlWebpackPlugin,它会把 webpack 生成的 bundles 塞到一个 HTML 文件里

执行webpack --config webpack.config.js

最终在 dist 下不仅有 index.js 文件,还会有一个 HTML

1
2
3
4
5
6
7
<!DOCTYPE html>
<html>
<head>
<meta charset=“UTF-8”></head>
<body>
<script type=“text/javascript” src=“index.js”></script></body>
</html>

配置

可以为 htmlWebpackPlugin 添加一些配置

1
2
3
4
new HtmlWebpackPlugin({
favicon: ‘./favicon.ico’,
title: ‘Webpack1’
})

我们为其生成的 HTML 指定了 favicon 及 title

生成的 HTML 如下:

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
<meta charset=“UTF-8”>
<title>Webpack1</title>
<link rel=“shortcut iconhref=“favicon.ico”></head>
<body>
<script type=“text/javascript” src=“index.js”></script></body>
</html>

原文作者: dgb8901,yinxing

原文链接: https://www.itwork.club/2019/02/24/html-webpack-plugin/

版权声明: 转载请注明出处

为您推荐

体验小程序「简易记账」

关注公众号「特想学英语」

企业微信服务商开发(六)