How to use CSS and CSS modules with webpack and TypeScript

174 views Asked by At

Currently, the cssLoader looks like this:

{
    test: /\.css$/i,
    use: [
        {
            loader: isDev ? 'style-loader' : MiniCssExtractPlugin.loader,
        },
        {
            loader: 'css-loader',
        },
        'postcss-loader',
    ],
};

Now, I need to configure the usage of CSS modules without giving up regular CSS.

In the global.d.ts file, I added the following:

declare module '*.module.css' {
    const styles: { [className: string]: string };
    export = styles;
}

The only thing left is to configure the loader for CSS modules. How can I do that?

1

There are 1 answers

0
Lust On

The question is resolved, it was just necessary to add the following to the loader:

options: {
    modules: {
        auto: true,
    },
},

The complete code looks like this:

{
    test: /\.css$/i,
    use: [
        {
            loader: isDev ? 'style-loader' : MiniCssExtractPlugin.loader,
        },
        {
            loader: 'css-loader',
            options: {
                modules: {
                    auto: true,
                },
            },
        },
        'postcss-loader',
    ],
};