0
votes

Currently, I have multiple css files under some react components. Those css files are required conditionally. However, css loader and extract text plugin include all the css files which is not required in a js file. Is there any way to exclude files by regex using test config or other way?

 test: /\.css$/,

lets say I have css files

bear.css
cat.css
styles.css
colors.css
... multiptle different css files 

I edit the regex correctly but still it include all css no matter what which i tested by leaving one comment on css file which should not be included on bundle.css

This is how I require css file

const css = require(`./styles/${config}`)

I will answer myself. Webpack's include exclude used to determine the file need to be transpile or not, which is nothing to do with excluding files from your bundle. For example, you add regex to exclude, it will still be in your bundle. However, it will not be processed or transpiled(depends on your loader you use). Therefore, you should use something likeignore loader to remove from your bundle.

1
The require cannot be used conditionally. All dependencies must be known before the compilation time, but there is something like require.context - Paweł
require can be used conditionally but not import - fiddlest

1 Answers

0
votes

According to webpack documentation you can include style-loader and css-loader in your webpack.config.js file:

config = {
    entry: "./app/Main.js",
    output: {
        publicPath: "/",
        path: path.resolve(__dirname, "app"),
        filename: "bundled.js"
    },
    mode: "development",
    module: {
        rules: [
        {
            test: /\.js$/,
            exclude: /(node_modules)/,
            use: {
            loader: "babel-loader",
            options: {
                presets: ["@babel/preset-react", ["@babel/preset-env", { targets: { node: "12" } }]]
            }
            }
        },
        {
            test: /\.css$/i,
            use: ['style-loader', 'css-loader'],
        },
        ]
    }
}

After that you could add css directly in your Main.js file

import Example from 'Example'; 

import './css/bear.css';
import './css/cat.css';
...