babel-plugin-react-css-modules is not matching styles with styleName

只谈情不闲聊 提交于 2019-12-10 17:47:45

问题


Issue

I am trying to use babel-plugin-react-css-modules in my React project for better performance as opposed to React CSS Modules.

However, the styles are being not applied correctly.

Cause

The version in <style> tag is wrapped with weird hypen, for example:

  • In the <style> tag: -components-Foo-___Foo__foo___1fcIZ-
  • On the DOM element class name: components-Foo-___Foo__foo___1fcIZ

Even if we are using the same localIdentName, the generated results are different from selectors in css and className on DOM element.

(Note: In babel-plugin-react-css-modules, the localIdentName is [path]___[name]__[local]___[hash:base64:5] as hard-coded in options.generateScopedName)

Any idea why there is a hypen-wrapper?


回答1:


Found the solution myself after some struggling.

Cause

This is due to a quirk of css-loader: if there are double quotes around localIdentName option, it will wrap the generated class name with hyphens.

Working Examples

So instead of doing this in webpack config:

{
    test: /\.(scss|sass)$/,
    use: [
        'style-loader?sourceMap',
        'css-loader?modules="true"&importLoaders="1"&localIdentName="[path]___[name]__[local]___[hash:base64:5]"',
        'sass-loader?sourceMap',
    ],
},

Do this:

{
    test: /\.(scss|sass)$/,
    use: [
        'style-loader?sourceMap',
        'css-loader?modules="true"&importLoaders="1"&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
        'sass-loader?sourceMap',
    ],
},

Or event better if you are using Webpack 2+

{
        test: /\.(scss|sass$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,    
              modules: true,
              sourceMap: true,
              localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
            }
          },
          'sass-loader'
        ]
}


来源:https://stackoverflow.com/questions/47675952/babel-plugin-react-css-modules-is-not-matching-styles-with-stylename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!