1.在src中创建webpack的入口文件index.js,index.html
2.src的同级目录下创建webpack.config.js
3.下载插件html-webpack-plugin
老规矩…初始化,下webpack webpack-cli,
下载大项目里,以后在这个大项目创建文件测试,就不用重复下包了
注意:下包是在最外面的大项目文件夹里下的。运行时要进入文件《打包Html资源》中运行
现在项目文件是这样的我们运行,终端输入webpack
如果【webpack】HtmlWebpackPlugin插件报错,The ‘compilation‘ argument must be an instance of Compilation,
似乎是webpack5和HtmlWebpackPlugin的兼容性问题
解决方法:
安装4.X的wepback和对应的HtmlWebpackPlugin
npm install webpack@4.44.2
这时候build文件夹里除了built.js还会生成一个index.html,
默认会创建一个空HTML文件,自动引入打包输出的所有资源(JS/CSS)
需求:需要有结构的HTML文件
复制’./src/index.html’文件,自动引入打包输出的所有资源(JS/CSS),所以我们不用自己引入资源
在webpack配置中,复制我们写的index.html,用build文件夹下的html文件打开网页
代码
index.html(这是我们自己写的,不是运行是生成的那个html文件)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="title">hello html</h1>
</body>
</html>
index.js
function add(x,y){
return x+y;
}
console.log(add(2,3));
webpack.config.js
/*
loader:1.下载 2.使用(配置loader)
plugins:1.下载 2.引入 3.使用
*/
const{resolve}=require('path');
//引入插件
const HtmlWebpackPlugin=require('html-webpack-plugin');
module.exports = {
entry: "./src/index.js",
output: {
filename: "built.js",
path: resolve(__dirname, "build"),
},
module: {
rules: [
//loader的配置
],
},
plugins: [
//构造函数直接用new调用
new HtmlWebpackPlugin({
//默认会创建一个空HTML文件,自动引入打包输出的所有资源(JS/CSS)
//需求:需要有结构的HTML文件
//复制'./src/index.html'文件,自动引入打包输出的所有资源(JS/CSS),所以我们不用自己引入资源
template:'./src/index.html'
}),
],
mode: "development"
};