简体   繁体   English

如何从 Webpack 中的 output 中排除某些.CSS 文件:?

[英]How to exclude certain .CSS file from output in Webpack:?

foo.js
foo.css
bar.css

foo.js includes foo.css . foo.js包括foo.css
And foo.css includes bar.css .并且foo.css包括bar.css

As result, I have bundle with bar.css .结果,我与bar.css捆绑在一起。 I want to exclude it.我想排除它。 I am also using MiniCssExtractPlugin since I nee to separate css and js files.我也在使用MiniCssExtractPlugin ,因为我需要分离 css 和 js 文件。

What I already tried:我已经尝试过的:

  • IgnorePlugin . IgnorePlugin It removes bar , but then MiniCssExtractPlugin fails because of it.它删除了bar ,但随后MiniCssExtractPlugin因它而失败。
  • null-loader for bar.css ( I tried both test with regexp and include/exclude). bar.css null-loader (我尝试使用正则表达式进行test并包含/排除)。 It simply doesn't work (it could be that I miss something.它根本不起作用(可能是我错过了一些东西。
  • Two oneOf rules for /\.css$/ : for with null-loader and another with everything else. /\.css$/的两个oneOf规则:用于null-loader和另一个用于其他所有内容。

Nothing works.没有任何效果。

What is the correct way to achieve it?实现它的正确方法是什么?

My webpack.config.js我的webpack.config.js

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({ }),
    new webpack.IgnorePlugin(/bar\.css$/)
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          'css-loader',
        ],
      },
    ],
  },
};

And the output和 output

ERROR in ./src/foo.css
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
Error: Cannot find module '-!../node_modules/css-loader/dist/cjs.js!./bar.css'

It seems that MiniCssExtractPlugin uses css-loader explicitly, so I can't skip module loading with configuration.似乎MiniCssExtractPlugin明确使用css-loader ,所以我不能跳过配置加载模块。

Solution is to use NormalModuleReplacementPlugin to replace bad file with empty one解决方案是使用NormalModuleReplacementPlugin将坏文件替换为空文件

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');

const pluginToIgnore = /bad_css\.css$/;
module.exports = {
    plugins: [
        new MiniCssExtractPlugin({}),
        new webpack.NormalModuleReplacementPlugin(
            pluginToIgnore,
            '!./empty.css'
        )
    ],
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader']
            },
        ],
    },
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM