![698b91a8eb2972bb2b3dd985daef4d88.png](https://img-blog.csdnimg.cn/img_convert/698b91a8eb2972bb2b3dd985daef4d88.png)
前言:
你可能也注意到了,html文件中的关于js的引用是我们手动写的,那假如我们改了输出路径或打包编译之后的文件名,那我们岂不是还要手动去修改html文件中的引用?我们怎么做到,像create-react-app中那样一旦你修改了某个文件内容,页面会自己刷新?我们来一步一步实现它们,当然,这一小节不仅仅只是为了完成这两点。
上一节:从零配置webpack 4+react脚手架(一)
自动编译html并引入js文件
public的index.html应该自动编译到dist目录,并且所有的js引用是自动添加的。你可以使用html-webpack-plugin插件来处理这个优化。
安装HtmlWebpackPlugin
在控制台执行以下代码:
npm install --save-dev html-webpack-plugin
在webpack.prod.config.js中配置plugins属性
const merge = require('webpack-merge');
const common = require('./webpack.common.config.js');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = merge(common, {
mode: 'production',
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
// 这里有小伙伴可能会疑惑为什么不是 '../public/index.html'
// 我的理解是无论与要用的template是不是在一个目录,都是从根路径开始查找
template: 'public/index.html',
inject: 'body',
minify: {
removeComments: true,
collapseWhitespace: true,
},
})
]
});
- filename:打包之后的html文件名字
- template:以我们自己定义的html为模板生成,不然我们还要到打包之后的html文件中写
- inject:在body最底部引入js文件,如果是head,就是在head中引入js
- minify:压缩html文件,更多配置点我
- removeComments:去除注释
- collapseWhitespace:去除空格
更多配置请点击官方README
删除index.html中手动引入的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>从零配置webpack4+react脚手架</title>
</head>
<body>
<div id=