webpack:当使用 2 个入口文件时,两个文件包含相同的 css - 有解决方法吗?

webpack: when using 2 entry files, both files include the same css - is there a workaround?

我使用了 2 个入口文件,startpage.jssubpage.js,并通过 HTMLWebpackPlugins 块参数将它们成功分配给了它们的 HTML 文件。

但是由于该解决方案需要在 startpage.jssubpage.js 中包含 CSS 文件,这使得 "double the trouble" (至少在构建过程中) ,我决定创建另一个文件 app_head,并将 import 'main.css' 语句放在那里。 (而且我还有一个 vendor 文件应该放在 HTML 的 header 中,根据文档应该通过添加 _head 来实现:https://github.com/architgarg/html-webpack-injector - 但这也不起作用...)

这是当前的 webpack 配置(摘录):

module.exports = {
  entry: {
    app_head: './src/css/main.css',
    vendor_head: './src/scripts/vendor/_all_vendor.js',
    startpage: './src/scripts/startpage.js',
    subpage: './src/scripts/subpage.js',
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, '../public'),
    publicPath: '/'
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './src/templates/index.ejs',
      chunks: ['app_head', 'vendor_head', 'startpage'],
      chunksConfig: {
        defer: ['startpage']
      },
      excludeChunks: ['subpage'],
      bodyCss: 'is-startpage',
    }),
    new HtmlWebpackPlugin({
      filename: 'publication.html',
      template: './src/templates/publication.ejs',
      chunks: ['subpage'],
      chunksConfig: {
        defer: ['subpage']
      },
      excludeChunks: ['startpage'],
      bodyCss: 'is-subpage',
    }),
    [...]

app_head.css放在HTML的head段很合适,但是也生成了一个无用的app_head.js,里面只包含webpack代码。不幸的是,我不知道如何在不排除 CSS.

的情况下排除该文件

有没有更好的方法来分离 CSS 生成过程而不产生开销或垃圾?

问题是你没有初始化 html-webpack-injector 插件。

// import above
const HtmlWebpackInjector = require('html-webpack-injector');

plugins: [
    new HtmlWebpackPlugin(...),
    new HtmlWebpackPlugin(...),
    new HtmlWebpackInjector() // add this in plugins array