5

I have a CSS Modules rule on webpack

{
            test: /\.css$/,
            loader: 'style-loader!css-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]'
}

Enabling modules modules=true gives me the following error:

ERROR in ./node_modules/css-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]!./src/global.css
Module not found: Error: Can't resolve '~/antd/dist/antd.css' in '[REDACTED]'
 @ ./node_modules/css-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]!./src/global.css 3:10-141
 @ ./src/global.css
 @ ./src/entry.jsx

This happens at the CSS line

@import '~/antd/dist/antd.css';

antd is a dependency that is in node_modules.

However, removing modules=true from the loader seems to generate no error from this import line.

I need CSS modules and I need to import this CSS. How can I fix this?

Berry
  • 2,143
  • 4
  • 23
  • 46

2 Answers2

1

You can stop css-loader to interpret @import statements by setting your config as follows

{
    test: /\.css$/,
    use: [ 
        {
            loader:'style-loader'
        }, 
        {
            loader: 'css-loader',
            options: {
                modules: true,
                localIdentName: '[name]__[local]___[hash:base64:5]',
                import: false
            }
        } 
    ]
}
John Peter
  • 441
  • 2
  • 13
  • The `@import` does not work anymore with this fix, and I need it to work. I also tried `import : true` and the import is still not working. – Berry Feb 01 '18 at 05:43
  • Hi from this link it seems others are facing similar issues with relative paths https://github.com/webpack-contrib/css-loader/issues/253 One thing that you could tryout is moving the antd into the same path as your other css files as Origslammer1 has said in that bug. But eventually you will have to track the updates manually. Or you could try creating aliases as stigi has done. – John Peter Feb 01 '18 at 07:03
1

Unfortunately, this is a known issue with CSS-loader. @imports don't work properly when modules are enabled.

There is an ugly solution for this, but a solution nonetheless.

What I did is I replaced the rule with this:

        {
            test: /^((?!\.module).)*css$/,
            use: [
                {
                    loader: 'style-loader'
                },
                {
                    loader: 'css-loader',
                }
            ]
        },
        {
            test: /\.module.css$/,
            loader: 'style-loader!css-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]'
        },

CSS files that require @import like in my case above, will now work, however these files cannot be imported in javascript as a CSS module.

CSS files that should be modular must be end with the file extension .module.css for CSS modules to work.

Berry
  • 2,143
  • 4
  • 23
  • 46