Dynamic CSS-Modules in ReactJS
ES2015 came with awesome dynamic imports, which opened a lot of possibilities for chunk splitting, hot reloading, … and also for dynamic builds. We use it heavily for building multiple versions of same app for different vendors. We were struggling a little how to use it with CSS-Modules with we fall in love instantly.
Problem
If you try to import css-module with name containing .env variable in webpack controlled environment you will end up with undefined error, because of chunk splitting.
TypeError: Cannot read property 'my-css-class-name' of undefined
Solution
Solution is quite simple as is stated in Webpack Module Methods documentation there is multiple options to tell webpack how to bundle your application. For us is important the option eager. Which tell webpack to bundle the dynamic import into the current chunk. Here is the code snippet:
let styles; import(/* webpackMode: "eager" */ `./LoginPanel.${process.env.REACT_APP_VARIABLE}.module.scss`).then( imported => { styles = imported.default; } );