webpack5 处理 html 资源文件

2023-05-03  本文已影响0人  暴躁程序员

一、webpack5 处理 html 资源文件

打包时自动生成 html 模板,并在 html 模板中自动引入打包后动态生成的资源文件路径,打包时自动压缩

  1. 初始化环境
npm init -y
  1. 安装环境依赖
npm install webpack cross-env webpack-cli html-webpack-plugin -D
  1. 在 package.json 中修改 scripts
"scripts": {
  "dev": "cross-env NODE_ENV=development webpack --config ./webpack.config.js --watch --progress --color ",
  "build": "cross-env NODE_ENV=production webpack --config ./webpack.config.js --progress --color "
},
  1. 新建入口文件 src/index.js
consle.log("hello world");
  1. 新建 src/index.html 模板文件
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>

  <body>
    <div id="app">
      <div>1</div>
      <div>2</div>
      <div>3</div>
    </div>
  </body>
</html>
  1. 创建 webpack.config.js 配置文件
    指定 html 文件的 template 模板文件,打包的输出路径,动态生成标题,设置 meta 标签内容
var path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: {
    app: "./src/index.js",
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name]-[hash:10].js",
  },
  mode: process.env.NODE_ENV,
  module: {
    rules: [],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: "My App", // 动态设置标题,打包后插入到 <title><%= htmlWebpackPlugin.options.title %></title>
      template: path.resolve(__dirname, "./src/index.html"), // 模板文件路径
      filename: "index.html", // 输出的html文件路径和文件名
      meta: {
        viewport: "width=device-width, initial-scale=1, shrink-to-fit=no",
        "theme-color": "#4285f4",
      },
    }),
  ],
};
  1. 打包测试
npm run dev
npm run build
  1. 打开dist/index.html查看打包结果
    生成环境下代码是压缩的
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>my title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no" />
    <meta name="theme-color" content="#4285f4" />
    <script defer="defer" src="app-2a54a39c14.js"></script>
</head>

<body>
    <div id="app">
        <div>1</div>
        <div>2</div>
        <div>3</div>
    </div>
</body>

</html>
上一篇 下一篇

猜你喜欢

热点阅读