E
E
Edward Treit2021-04-19 05:08:27
React
Edward Treit, 2021-04-19 05:08:27

How to properly work with CSS modules in React?

Good day. For a long time I did not work on the front, I decided to write a small project. I have a template that I decided to use, but move the build from Webpack 4 to 5. The set is standard: React + TypeScript, Redux, Sass. I use CSS modules. I import styles into components like this: And to assign a class to any element, I wrote like this: And everything worked. But now, to get the desired effect, you have to write like this:

const styles = require('./styles.module.scss');
<h1 className={styles.title}>Hello World!</h1>

<h1 className={styles.default.title}>Hello World!</h1>

If I do not add default, then I get in the Module import:
Module {
  default: Object
    title: "title___1pnWo"
  __proto__: Object
  Symbol(Symbol.toStringTag): "Module"
  __esModule: true
  get default: () => (__WEBPACK_DEFAULT_EXPORT__)
  __proto__: Object
}

I re-read the documentation, but I did not find anything new about this writing style. For css, the config in Webpack is as follows:
test: /\.(scss|sass|css)$/,
use: [
      {
        loader: mode === 'development' ? 'style-loader' : MiniCssExtractPlugin.loader,
      },
      {
        loader: 'css-loader',
        options: {
            sourceMap: mode === 'development',
            importLoaders: 3,
            modules: {
              localIdentName: '[local]___[hash:base64:5]',
            },
          },
      },
      {
        loader: 'sass-loader',
        options: {
          sourceMap: mode === 'development',
          sassOptions: {
            outputStyle: 'expanded',
          },
        },
      },
      {
        loader: 'sass-resources-loader',
        options: {
          sourceMap: mode === 'development',
          resources: `${resourcesPath}/**/*.scss`,
        },
      },
    ]

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2021-04-19
@Seasle

Option 1 - use import/export.
Option 2 - require('file').default.

E
Edward Treit, 2021-04-19
@EdMSL

Option 1 tried. The second yes, it is possible so, but I would understand the reason for this. Why do we need to add default now? If this is how it works now, then why is there not a word in the documentation (in the css-loader docs).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question