webpack如何打包html
时间: 2024-06-01 18:03:47 浏览: 271
webpack本身不会自动打包html文件,需要使用html-webpack-plugin插件来实现。该插件会在打包过程中自动生成一个html文件,并将打包后的js文件自动引入到html文件中。
使用步骤如下:
1. 安装html-webpack-plugin插件:
```
npm install html-webpack-plugin --save-dev
```
2. 在webpack配置文件中引入该插件,并进行配置:
```javascript
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// ...
plugins: [
new HtmlWebpackPlugin({
title: 'My App', // 设置生成的html文件的标题
template: './src/index.html' // 指定模板文件路径
})
]
}
```
3. 在src目录下创建一个index.html文件作为模板文件,在文件中可以使用ejs语法来引用打包后的js文件:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="app"></div>
<script src="<%= htmlWebpackPlugin.files.chunks.main.entry %>"></script>
</body>
</html>
```
在模板文件中,可以通过ejs语法来引用htmlWebpackPlugin对象中的数据,如htmlWebpackPlugin.options.title表示生成的html文件的标题,htmlWebpackPlugin.files.chunks.main.entry表示打包后的主要入口文件的路径。
4. 运行webpack打包命令,生成html文件:
```
npm run build
```
执行该命令后,会在dist目录下生成一个index.html文件,其中引用了打包后的js文件。
阅读全文
相关推荐















