我正在一个弹出的反应 cli 上构建一个项目。我弹出它的原因是因为将生成多个页面和一些我想要制作的独立脚本,并让它们利用 ES6 和样板提供的调试工具。
我的问题是,在使用该技术构建多个页面时, html-webpack-plugin
使用每个页面的两个脚本构建生成的 HTML 文件。
那么,让我们看一下基本的入口点
这是我的基本 web pack 配置。
...
entry: {
devServerClient : require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
...pages,
},
...
如您所见,我正在使用与样板一起提供的相同的热模块重新加载内容,但随后我偏离了从另一个页面所需的 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;
这就是我动态生成多个条目的方式。这部分代码工作正常,但我想我会发布它,以防万一我错过了这里需要发生的事情。
接下来我们有实际的插件部分。我在模块化代码时采用了类似的方法,所以这是配置中的那部分(webpack 对象的根级别):
...
plugins: [
// Generates an `index.html` file with the <script> injected.
...HtmlWebpackPlugins,
...
]
...
同样,我将它们散布进去,生成它们的脚本如下所示:
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;
这个脚本在这里为每个条目生成类的多个实例HtmlWebpackPlugin
,我们还根据应用程序所在文件夹的名称来命名 html 文件。这满足了他们的问题部分中的技术。
然后问题发生在生成的 HTML 页面中。请注意,所有文件夹的脚本都被注入到每个应用程序中:
如您所见,添加了每个应用程序的 CSS 和 JS。这发生在两个页面上。我只想要每个页面的相关 CSS 和 JS。
知道这里发生了什么吗?