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?
Unfortunately, this is a known issue with CSS-loader. @import
s 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.