问题描述
项目中同时使用 babel-plugin-react-css-modules
和 cssLoader
对样式文件进行处理,前者讲 jsx 中的 styleName 转化为 className,后者将样式文件中类转化为固定格式的字符串。
两者共同使用 [path]___[name]__[local]___[hash:base64:5]
作为转化后的样式格式。
然而,在 mac 上正常应用的样式,在windows 上不能生效。
问题分析
查看源码,发现 cssLoader
转换格式的方法使用了 interpolateName
(github地址)。babel-plugin-react-css-modules
使用了 genericNames
,再查看 genericNames
的源码,发现其最终也是调用了 interpolateName
方法,(github地址),和 cssLoader
的区别在于,多了一层对 \
的转换,(github地址)。
即两者的区别为,babel-plugin-react-css-modules
使用 generic-names
将 windows 路径中的 \
转化为 /
之后再传给 interpolateName
处理。
解决方法
找到了原因,就有了解决方法。思路为,利用 cssLoader
中的 getLocalIdent
配置,传入自定义的转化方法,使其转化规则与 babel-plugin-react-css-modules
保持一致。
代码如下:
import genericNames from 'generic-names';
import path from 'path';
const GENERATE_PATH = '[path]___[name]__[local]___[hash:base64:5]';
function generateScopedName(localName, filePath) {
const relativePath = path.relative(process.cwd(), filePath);
return genericNames(GENERATE_PATH)(localName, relativePath);
}
// cssLoader 配置
getLocalIdent: function(context, _, localName) {
return generateScopedName(localName, context.resoucePath);
}
网友评论