HtmlWebpackPlugin 可以仅使用 [name] 文件夹中的包吗?

问题描述 投票:0回答:1

我有一个 webpack.config.js,它扫描配置文件夹以在不同的输出文件夹中构建不同的包,以便每个输出文件夹都可以是一个独立的网站。对于每个输出文件夹,我想将文件夹的 contenthash 捆绑注入 src/template.html 以生成写入每个输出文件夹的 index.html。

当想要使用 html 模板时,官方 webpack 文档推荐 HtmlWebpackPlugin,但是当我尝试(使用插件的 v5.6.0)时...

plugins: [
    new HtmlWebpackPlugin({
        filename:  '[name]index.html'
        ,template:  './src/template.html'
    })
]

...它将所有输出文件夹中的所有包注入到每个index.html中。

我查看了插件的 github 页面及其 index.js 的源代码,但我找不到一种方法将每个 index.html 的捆绑包限制为同一输出文件夹中的捆绑包。

我无法使用

chunks
属性,除非它可以采用 [contenthash].js 之类的值 文档仅提及完全指定的值,而不提及占位符。

webpack-5 html-webpack-plugin
1个回答
0
投票

你可以尝试使用现代的 html-bundler-webpack-plugin

使用此插件您可以直接在每个 HTML 模板文件中定义 SCSS 和 JS/TS 源文件。 该插件解析模板中的样式、脚本、图像、字体等源文件,并在生成的 HTML 中用输出文件名替换它们。

例如./src/template.html:

<html>
  <head>
    <!-- relative path to SCSS source file -->
    <link href="../scss/style.scss" rel="stylesheet" />
    <!-- relative path to JS source file -->
    <script src="../app/main.js" defer="defer"></script>
  </head>
  <body>
    <h1>Hello World!</h1>
    <!-- relative path to image source file -->
    <img src="./picture.png" />
  </body>
</html>

生成的 HTML 包含输出文件名的 URL:

<html>
  <head>
    <link href="css/style.05e4dd86.css" rel="stylesheet" />
    <script src="js/main.f4b855d8.js" defer="defer"></script>
  </head>
  <body>
    <h1>Hello World!</h1>
    <img src="img/picture.58b43bd8.png" />
  </body>
</html>

Webpack 配置:

const HtmlBundlerPlugin = require('html-bundler-webpack-plugin');

module.exports = {
  plugins: [
    new HtmlBundlerPlugin({
      entry: [
        {
          import: 'src/template.html', // template file
          filename: 'index.html', // => dist/index.html
        },
      ],
      js: {
        // JS output filename
        filename: 'js/[name].[contenthash:8].js',
      },
      css: {
        // CSS output filename
        filename: 'css/[name].[contenthash:8].css',
      },
    }),
  ],
  module: {
    rules: [
      {
        test: /\.(css|sass|scss)$/,
        use: ['css-loader', 'sass-loader'],
      },
      {
        test: /\.(ico|png|jp?g|webp|svg)$/,
        type: 'asset/resource',
        generator: {
          filename: 'img/[name].[hash:8][ext][query]',
        },
      },
    ],
  },
};
© www.soinside.com 2019 - 2024. All rights reserved.