Webpack——02——打包html资源

2023-05-16

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"
};

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Webpack——02——打包html资源 的相关文章