应用场景:当我们配置了webpack自动打包工具后,通过 http://localhost:8080/ 访问到的是文件夹根目录,而没有直接打开html页面,如果要打开html页面需要在界面中点击指定的html页面才行。所以在这儿就用到webpack预览页面配置,直接把要在浏览器中访问的页面放在在根目录内存中。
在这里我使用VScode编辑器
在vscode中要停止自动打包,使用ctrl+c快捷键,选择 Y 接口停止自动打包功能
- 第一步:vscode终端,在项目根目录中运行 npm install html-webpack-plugin -D、安装生成预览页面的插件
- 第二步:修改目录中的webpack.config.js文件头部区域,添加配置如下:
//导入生成预览页面的插件,得到一个构造函数
const HtmlWebpackPlugin = require('html-webpack-plugin');
const htmlPlugin = new HtmlWebpackPlugin({//创建插件的实例对象
template:'./src/index.html',//指定要用到的模板文件
filename:'index.html'//指定生成的文件的名称,该文件存在于内存中,在目录中不显示
})
- 第三步:修改 webpack.config. js文件中向外暴露的配置对象,新增如下配置节点:
plugins:[htmlPlugin],// plugins 数组是webpack 打包期间会用到的一些插件列表
具体webpack.config.js配置如下:
const path = require('path');//导入node.js中专门操作路径的模块
//导入生成预览页面的插件,得到一个构造函数
const HtmlWebpackPlugin = require('html-webpack-plugin');
const htmlPlugin = new HtmlWebpackPlugin({//创建插件的实例对象
template:'./src/index.html',//指定要用到的模板文件
filename:'index.html'//指定生成的文件的名称,该文件存在于内存中,在目录中不显示
})
module.exports = {
// entry:path.join(__dirname,'./src/index.js'),//打包入口文件的路径
entry:{
//打包入口文件的路径
entry:path.join(__dirname,'./src/index.js')
},
output:{
path:path.join(__dirname,'./dist'),//输出文件的存放路径
filename:'button.js'//输出文件的名称
},
plugins:[htmlPlugin],// plugins 数组是webpack 打包期间会用到的一些插件列表
mode:'development' // mode用来指定构建模式
}
然后直接在浏览器中访问 http://localhost:8080/
这样就能直接访问了,而不需要在点击html文件来查看页面的预览了
注意:这儿放根目录html文件是放在内存中的,实际项目根目录不存在这个html文件