styles undefined when using CSS Modules with r
I'm having a problem when using CSS Modules with React + Webpack where my variable styles is undefined and nothing can be found. I'm using the following in my project:
"devDependencies": {
"@babel/core": "^7.24.7",
"@babel/preset-env": "^7.24.7",
"@babel/preset-react": "^7.24.7",
"babel-loader": "^9.1.3",
"css-loader": "^7.1.2",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.6.0",
"style-loader": "^4.0.0",
"webpack": "^5.91.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4"
}
My webpack.config.js:
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js'
},
plugins: [
new HTMLWebpackPlugin({
template: './src/index.html'
})
],
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react'
]
}
}
},
{
test: /\.(png)$/i,
use: [
{
loader: 'file-loader',
}
]
},
{
test: /\.css$/,
use: ['style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: true
}
}
]
}
]
}
}
I have a file called TestComponent.js which has:
import React from 'react';
import styles from './Test.module.css';
function TestComponent() {
console.log(styles);
return (
<div className={styles.a}>
<p>
Random text Random text Random text Random text Random text Random text
</p>
</div>
);
}
export default TestComponent;
My css file is called Test.module.css:
.a {
border-style: solid;
border-color: green;
border-width: 2px;
}
Not sure what is going wrong?
EDIT -> Using: "import * as styles" seems to work but every guide I see online shows the way I did it above, so I'm confused as to why it wont work?
EDIT 2 -> I found that using "import { a } from './Test.module.css';" works, but I still cannot get it to work if I try to do it the above way.
EDIT 3 -> If I remain using styles but don't actually use it in a className it does get added into the index.html header as a style tag. I'm just unable to use it in the component.
Here is a github repo if it helps: https://github.com/randobanohando/testprj