The way how to using CSS format in React

Let’s find out the way how to modify your React project when you want to operate CSS format files in yours

If it doesn’t work with showing message like below. the reason doesn’t operate is because you did’t install the things relate to CSS Styling

so now, we will install 2 packages using npm.

they are css-loader and style-loader.

1. Let’s install css-loader, style-loader via npm

follow command below at your React project folder

1
.../my_react_express > npm install --save-dev css-loader style-loader

2. Update your webpack.config.js file

add code below in your webpack.config.js

1
2
3
4
{
test: /\.css$/,
use: ['css-loader', 'style-loader']
}

Originally, your webpack.config.js maybe is like below.

Before

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
module.exports = {
entry: [
'./src/index.js'
],

module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},

output: {
path: __dirname + '/public',
filename: 'bundle.js'
}
};

Let’s modify it like below.

After

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
module.exports = {
entry: [
'./src/index.js'
],

module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
/////////////////////////////////////////////////////// START NEW CODE
{
test: /\.css$/,
use: ['css-loader', 'style-loader']
}
/////////////////////////////////////////////////////// END NEW CODE
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},

output: {
path: __dirname + '/public',
filename: 'bundle.js'
}
};

Don’t miss the comma ‘,’ between the code associated with babel-loader and css-loader when you modify your webpack.config.js

If you do the above successfully, then your React system will understand .css files

Share