1、安装:
cnpm i html-webpack-plugin -D
2、webpack.config.js中配置plugins属性:
const path = require("path")
const htmlWebpackPlugin = require("html-webpack-plugin") // 导入 在内存中自动生成html文件 的插件
// 创建一个插件的实例对象
const htmlPlugin = new htmlWebpackPlugin({
template: path.join(__dirname, "./src/index.html"), // 源文件
filename: "index.html" // 生成的 内存中首页的 名称
})
module.exports = {
mode: 'production', // development 或 production
plugins: [
htmlPlugin
]
}
其中package.json(和其它地方一样,没什么特殊的):
{
"name": "wp4-1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open chrome --port 3000 --hot --host 127.0.0.1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1"
}
}
3、cmd中运行:npm run dev
4、浏览器中运行:http://127.0.0.1:3000/
5、查看生成的首页index.html文件的源码,发现插件自动添加了“<script type="text/javascript" src="main.js"></script>”:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="../main.js"></script>
</head>
<body>
<h1>首页</h1>
<script type="text/javascript" src="main.js"></script></body>
</html>