How to enable React CSS modules on Symfony and Webpack
If you want to use React CSS modules for your React app and you are using Symfony as backend, you can follow this easy tutorial to include this feature.

Step 1: start with a clean Webpack configuration (optional)
If your project is not so recent, you can consider starting with a clean Webpack configuration. But if you are sure about your Webpack configuration, you can skip this step.
To simplify this tutorial, I had simply removed Webpack and reinstalled it.
- composer remove symfony/webpack-encore-bundle
- remove your webpack.config.js file from the project root.
- composer require symfony/webpack-encore-bundle
After that, you will probably face some errors such as package incompatibility, etc.
Step 2: add postcss-loader and configure postcss.config.js
To use CSS modules in React, you need to add postcss-loader to your package.json. Just run:
yarn add --dev postcss-loader cssnano
Now you should create the postcss.config.js file in the project root directory with this simple content:
module.exports = {
plugins: {
'cssnano': {} }
}
Step 3: setup the webpack.config file
Now it’s time to add some important configuration in the webpack.config.js… In this case, I’ll list only the essentials configuration for a react project with CSS modules. Uncomment and/or add these configurations:
.enableSassLoader() //enable SCSS file.configureCssLoader(options => { options.modules = true })
.enablePostCssLoader().enableReactPreset()
At the end of this process, you should have a configuration similar to this:
var Encore = require('@symfony/webpack-encore');
Encore
.setOutputPath('public/build/')
.setPublicPath('/build')
.addEntry('js/app', './assets/js/app.js')
.disableSingleRuntimeChunk()
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
.enableSassLoader()
.configureCssLoader(options => { options.modules = true })
.enablePostCssLoader() .autoProvidejQuery()
.enableReactPreset()
;
module.exports = Encore.getWebpackConfig();
Step 4: set your first react component with CSS module
The boring configuration part is finished. It’s time to set your first CSS module in React. Let’s assume to have this project structure and that you want to set a CSS module for your Header component.
/assets
/js
/components
/Header
index.jsx
style.scss /containers
/App
index.jsx
style.scss
With this structure, we can set the CSS module inside the index.jsx in the Header folder.
/assets/js/components/Header/index.jsximport React from "react";
import styles from "./styles.scss";
export default function Header() {
return (
<div className={styles.header}>
<p>Header</p>
</div>
);
}
Your React component is now ready to read a ‘.header’ class inside your styles.scss file. So let’s add that.
.header {
background: blue;
}
Launch your project, you will now see your new component fully working with CSS modules. a