babel-plugin-react-css-modules与styleName的样式不匹配 [英] babel-plugin-react-css-modules is not matching styles with styleName

查看:465
本文介绍了babel-plugin-react-css-modules与styleName的样式不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我正在尝试使用 babel-plugin-与 React CSS Modules 相比,我的React项目中的react-css-modules 具有更好的性能.

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.

原因

<style>标记中的版本用奇怪的连字符包装,例如:

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

  • <style>标记中:-components-Foo-___Foo__foo___1fcIZ-
  • 在DOM上 元素类名称:components-Foo-___Foo__foo___1fcIZ
  • In the <style> tag: -components-Foo-___Foo__foo___1fcIZ-
  • On the DOM element class name: components-Foo-___Foo__foo___1fcIZ

即使我们使用相同的localIdentName,生成的结果 与DOM元素上的CSS和className中的选择器不同.

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

(注意:在babel-plugin-react-css-modules中,localIdentName[path]___[name]__[local]___[hash:base64:5]如硬编码在 options.generateScopedName)

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

有人知道为什么要有一个hypen-wrapper吗?

Any idea why there is a hypen-wrapper?

推荐答案

在挣扎之后自己找到了解决方案.

Found the solution myself after some struggling.

这是由于css-loader引起的:如果localIdentName选项周围有双引号,它将用连字符将生成的类名包装起来.

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.

因此,不要在webpack配置中这样做:

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',
    ],
},

执行此操作:

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

或者,如果您使用的是Webpack 2+,则更好.

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'
        ]
}

这篇关于babel-plugin-react-css-modules与styleName的样式不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆