Create-react-app creates a project, how to set CSS modularity?

Cause of the problem

Recently, I was researching react and built a project based on the officially provided create-react-app scaffolding. However, when CSS is introduced like the following, it will be found that the whole world will take effect, which is obviously unreasonable. So, how to set it?

import './header.css'; // 这样引入相当于全局引入了

CSS Modularity

We know that in webpack, CSS files can be packaged through CSS-loader and style-loader . There are some configuration items in it. CSS can be packaged into a module and then imported. Generally, webpack is set like this.

{
  test: /\.css$/,
  loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[name]_[local]__[hash:base64:5]'
}

When modules is true, the CSS is packaged as the control parameter of the module

How to set it up?

For projects created with create-react-app, we must first find out where the configuration file is. The default path of the file is: \node_modules\react-scripts\config\webpack.config.dev.js , and then find the following code, add A parameter modules: true is fine:

          {
            test: /\.css$/,
            use: [
              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                  modules: true
                },
              },
              {
                loader: require.resolve('postcss-loader'),
                options: {
                  // Necessary for external CSS imports to work
                  // https://github.com/facebookincubator/create-react-app/issues/2677
                  ident: 'postcss',
                  plugins: () => [
                    require('postcss-flexbugs-fixes'),
                    autoprefixer({
                      browsers: [
                        '>1%',
                        'last 4 versions',
                        'Firefox ESR',
                        'not ie < 9', // React doesn't support IE8 anyway
                      ],
                      flexbox: 'no-2009',
                    }),
                  ],
                },
              },
            ],
          },

finally

Import in the modules you need to use

import headerCss from './header.css';

Of course, don't forget to change the configuration of the production line, that is, the webpack.config.prod.js file

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325317145&siteId=291194637