Skip to main content

Import CSS class names in JS

Required: css-loader >= 7.0.0

To import style class names in JS, add in the webpack config the modules option into css-loader:

{
test: /\.(css)$/,
use: [
{
loader: 'css-loader',
options: {
modules: {
localIdentName: '[name]__[local]--[hash:base64:5]',
exportLocalsConvention: 'camelCase',
},
},
},
],
},

For example there is ./style.css file:

.error-message {
color: red;
}

In ./main.js file you can use the class name with camelCase:

import styles from './style.css';

element.innerHTML = `<div class="${styles.errorMessage}">`;

The imported styles object contains generated class names like followings:

{
errorMessage: 'main__error-message--gvFM4',
}

Read more information about CSS Modules.