想请教大家一个关于css Modules 配置的问题 ^_^ ~~~

#1

我在 Create-react-app 2 创建的脚手架里配置了css modules,但是 页面上class类名显示undefined,请问怎么解决?下面是我的配置步骤和页面显示,拜托您帮忙看看
1:在webpack.config.dev.js里开启 modules: true,

 {
              test: cssRegex,
              exclude: cssModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                sourceMap: isEnvProduction && shouldUseSourceMap,
              }),
              
              sideEffects: true,
            },
            // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
            // using the extension .module.css
            {
              test: cssModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                sourceMap: isEnvProduction && shouldUseSourceMap,
                modules: true,
                getLocalIdent: getCSSModuleLocalIdent,
              }),
            },
            // Opt-in support for SASS (using .scss or .sass extensions).
            // By default we support SASS Modules with the
            // extensions .module.scss or .module.sass
            {
              test: sassRegex,
              exclude: sassModuleRegex,
              use: getStyleLoaders(
                {
                  importLoaders: 2,
                  modules: true ,
                  sourceMap: isEnvProduction && shouldUseSourceMap,
                },
                'sass-loader'
              ),
              // Don't consider CSS imports dead code even if the
              // containing package claims to have no side effects.
              // Remove this when webpack adds a warning or an error for this.
              // See https://github.com/webpack/webpack/issues/6571
              sideEffects: true,
            },
            // Adds support for CSS Modules, but using SASS
            // using the extension .module.scss or .module.sass
            {
              test: sassModuleRegex,
              use: getStyleLoaders(
                {
                  importLoaders: 2,
                  sourceMap: isEnvProduction && shouldUseSourceMap,
                  modules: true,
                  getLocalIdent: getCSSModuleLocalIdent,
                },
                'sass-loader'
              ),
            },


在render里打印了style ,style对象为空

#2

看了下,估计webpack配置有问题
建议参考:
http://www.ruanyifeng.com/blog/2016/06/css_modules.html

#3

阮一峰16年写的文章,参考价值比较低,不过还是谢谢你。我用的是最新版的react脚手架,webpack配置封装的比较深,已经解决了

#4

好的,我项目中之前也用到过,不过后来被移除了。

#5
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;

后缀名 .module.css 才会自动开启css module 不然就按常规css走

文档上也有说

源码你也看了 不过没看仔细

1 Like
#6

这个怎么解决的?求助~~~~qq980373688

#7

感谢你!话说这个源代码你指的什么源代码:smiley: