Home > Enterprise >  import css does not work for class name with dashes for Webpack 5 and css loader 5
import css does not work for class name with dashes for Webpack 5 and css loader 5

Time:05-06

Trying to get a third party library that is importing css to work with my app.

I am using webpack v5 and css-loader v5. Since the upgrade from webpack v4 to v5, the 3rd party library styles are no longer working because css-loader doesn't allow named exports, hence

import('./styles.css').then((styles) => console.log(styles))

will yield something like styles.default.xxx instead of styles.xxx

A workaround would be setting namedExport option to be true in css-loader. This will enable me to access styles.xxx without the default. However if I set namedExport to be true in css-loader, I can no longer import classes with dashes (e.g. "btn-focused" because css-loader will convert it to "btnFocused" and the third party library refers to the styles as styles['btn-focused']). I see an option exportLocalsConvention in css-loader, however this option is restricted to 'camelCaseOnly' or 'dashesOnly' when namedExport is set to true, and both of these options do not help.

CodePudding user response:

Did you try style-loader? Give the following configuration a try! It works in dynamic imports:

use: [
  {
    loader: 'style-loader',
    options: {
      esModule: false,
    },
  },
  {
    loader: 'css-loader',
    options: {
      esModule: false,
      modules: {},
    },
  }
]

Feel free to let me know if there is any problem with it :)

  • Related