关于webpack5:Webpack5打包多入口的html项目

31次阅读

共计 2133 个字符,预计需要花费 6 分钟才能阅读完成。

具体配置如下:

const {resolve} = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
  // 多入口
  entry: {page1: ["./src/assets/js/page1.js"],
    page2: ["./src/assets/js/page2.js"],
    page3: ["./src/assets/js/page3.js"],
  },
  output: {path: resolve(__dirname, "dist"),
    filename: "assets/js/[name][hash:10].js",
  },
  module: {
    rules: [{ test: /\.css$/, use: [MiniCssExtractPlugin.loader, "css-loader"] },
      {test: /\.(png|jpg|jpeg|gif|icon|webp)$/,
        type: "asset",
        parser: {dataUrlCondition: () => {return false; // 不在 css 中生产 base64,全副打包为图片资源},
        },
        generator: {filename: "assets/images/[name][hash:10][ext]",
        }
      },
      {test: /\.(woff|woff2|svg|eot|ttf)\??.*$/,
        type: "asset/resource",
        generator: {filename: "assets/font/[name][hash:10][ext]",
        }
      },
      {test: /\.(htm|html)$/i,
        use: ["html-withimg-loader"], // 解决 html 中标签引入的图片门路
      }
    ],
  },
  plugins: [
    new CopyWebpackPlugin({
      patterns: [
        {
          from: "./src/assets/js/common", // 想要复制的文件夹
          to: "assets/js/common", // 复制在哪个文件夹
        },
        {
          from: "./src/assets/images/icon", // 想要复制的文件夹
          to: "assets/images/icon", // 复制在哪个文件夹
        },
      ],
    }),
    new HtmlWebpackPlugin({
      template: "./src/index1.html", // webpack 模板的绝对或绝对路径
      filename: "index1.html", // 将 HTML 写入到的文件
      chunks: ["page1"], // 须要增加的 js 文件
      hash: true, // 将 css 和 js 退出 hash 值
      inject: "body", // 所有资源注入的地位
      scriptLoading: "blocking", // script 标签加载形式
      minify: {
        // collapseWhitespace: true,
        removeComments: true,
      },
    }),
    new HtmlWebpackPlugin({
      template: "./src/index2.html",
      filename: "index2.html",
      chunks: ["page2"],
      hash: true,
      inject: "body",
      scriptLoading: "blocking",
      minify: {
        // collapseWhitespace: true,
        removeComments: true,
      },
    }),
    new HtmlWebpackPlugin({
      template: "./src/index3.html",
      filename: "index3.html",
      chunks: ["page3"],
      hash: true,
      inject: "body",
      scriptLoading: "blocking",
      minify: {
        // collapseWhitespace: true,
        removeComments: true,
      },
    }),
    new MiniCssExtractPlugin({// chunkFilename: "[id].css",
      filename: "assets/css/style[hash:10].css",
    }), // 将 css 提取到独自的文件中
    new CssMinimizerWebpackPlugin(), // 对 css 进行压缩],
  // mode: "development",
  mode: "production",
};

打包前须要留神如下几点:

  • html 中通过 link 引入的 css,须要替换为:在 js 中通过 import 形式引入
  • html 中通过 script 引入的 page1.js、page2.js、page3.js 等入口文件,须要先正文

正文完
 0