html-webpack-plugin 多个入口点添加所有脚本

Phi*_*l_t 5 javascript multiple-entries webpack html-webpack-plugin

我正在弹出的反应 cli 上构建一个项目。我弹出它的原因是因为将生成多个页面和一些我想要制作的独立脚本,并让它们利用样板提供的 ES6 和调试工具。

我的问题是,在使用该技术构建多个页面时, html-webpack-plugin会使用每个页面的两个脚本构建生成的 HTML 文件。

那么,让我们来看看基本的入口点

这是我的基本网络包配置。

...
entry: {

      devServerClient : require.resolve('react-dev-utils/webpackHotDevClient'),
      // Finally, this is your app's code:
      ...pages,

    },
...
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在使用与样板一起提供的相同热模块重新加载内容,但随后我偏离了从另一个页面所需的 pages 变量中传播值:

const glob = require("glob");
const path = require("path");

const input_path = path.resolve(__dirname, "../src/apps/*/index.js");
const apps_directories = glob.sync(input_path);

let pages = {};

// Loop through them and append them to the pages object for processing.
apps_directories.map(function (app_directory) {
    const split_name = app_directory.split("/");
    pages[split_name[split_name.length - 2]] = app_directory;
});

module.exports = pages;
Run Code Online (Sandbox Code Playgroud)

这就是我动态生成多个条目的方式。这部分代码工作正常,但我想我会发布它以防万一这里需要发生我遗漏的事情。

接下来我们有实际的插件部分。我在模块化代码时采用了类似的方法,所以这是配置中的那部分(webpack 对象的根级别):

...
plugins: [
    // Generates an `index.html` file with the <script> injected.
    ...HtmlWebpackPlugins,
    ...
]
...
Run Code Online (Sandbox Code Playgroud)

同样,我将它们展开,生成这些的脚本如下所示:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const pages = require("./multiplePaths");
const paths = require("./paths");

const NODE_ENV = process.env.NODE_ENV;

let HtmlWebpackPlugins = [];

Object.keys(pages).map(function (fileName) {
    if (NODE_ENV === "development") {
        HtmlWebpackPlugins.push( new HtmlWebpackPlugin({
            inject: true,
            template: paths.appHtml,
            filename: `${fileName}.html`,
        }));
        return;
    }

    HtmlWebpackPlugins.push(new HtmlWebpackPlugin({
        inject: true,
        template: paths.appHtml,
        filename:  `${fileName}.html`,
        minify: {
            removeComments: true,
            collapseWhitespace: true,
            removeRedundantAttributes: true,
            useShortDoctype: true,
            removeEmptyAttributes: true,
            removeStyleLinkTypeAttributes: true,
            keepClosingSlash: true,
            minifyJS: true,
            minifyCSS: true,
            minifyURLs: true,
        },
    }));
});

module.exports = HtmlWebpackPlugins;
Run Code Online (Sandbox Code Playgroud)

这里的脚本为HtmlWebpackPlugin每个条目生成类的多个实例,我们还根据应用程序所在文件夹的名称为 html 文件命名。这满足他们问题部分中的技术

然后问题发生在生成的 HTML 页面中。请注意,所有文件夹的脚本都注入到每个应用程序中:

在此处输入图片说明

如您所见,添加了每个应用程序的 CSS 和 JS。这发生在两个页面上。我只想要每个页面的相关 CSS 和 JS。

知道这里发生了什么吗?

小智 6

如果您只想在每个页面内添加一些块,您需要指定哪些块作为脚本包含在 html 中:

HtmlWebpackPlugins.push(new HtmlWebpackPlugin({
    inject: true,
    template: paths.appHtml,
    filename:  `${fileName}.html`,
    chunks: [filename], // add any chunks you need here (for example, chunk with libraries
    ....
});
Run Code Online (Sandbox Code Playgroud)