我正在尝试在现有的 React 项目中使用 babel-plugin-react-css-modules。大多数组件都可以正常工作,但是将样式“传递”给子组件存在问题。
我有一些这样的父组件:
SearchBlock/index.js
import "./style.scss"
import { SettingsIcon } from "../../Icons"
...
<div styleName='SearchBlock'>
<SettingsIcon size='17' color='#2991F5' />
</div>
SearcBlock/style.scss
.SearchBlock {
...
.SettingsIcon {
margin-right: 7px;
}
...
}
还有像这样的子组件
设置图标/index.js
const SettingsIcon = (props) => {
...
return (
<svg
width={size}
height={size}
viewBox='0 0 24 24'
fill='none'
xmlns='...'
className='SettingsIcon'
>
...
因此图标在不同的组件中具有适当的样式。
我在生成的 css 文件中得到了什么:
.src-components-Search-SearchBlock-___style__SearchBlock___2MeUy .src-components-Search-SearchBlock-___style__SettingsIcon___3SWQh {
margin-right: 7px; }
似乎是正确的。但是,子元素呈现如下:
<svg ... class="SettingsIcon"><</svg>
代替
<svg ... class="src-components-Search-SearchBlock-___style__SettingsIcon___3SWQh"><</svg>
我不能在 settingsIcon 中使用styleName,因为 webpack 在不导入至少一个样式表的情况下会抛出错误。
有没有什么办法解决这一问题?
我的配置
webpack.common.js
...
test: /\.s?css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
modules: {
mode: 'local',
localIdentName: isProd
? '[hash:base64]'
: "[path]___[name]__[local]___[hash:base64:5]",
},
sourceMap: true,
importLoaders: 1,
onlyLocals: false,
},
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
},
...
babel.config.js
const isProd = process.env.NODE_ENV === 'production';
function createReactCssModulesPlugin() {
return [
"react-css-modules",
{
filetypes: {
".scss": {
syntax: "postcss-scss",
plugins: [
"postcss-import-sync2",
[
"postcss-nested",
{
bubble: ["@include"],
preserveEmpty: true,
},
],
],
},
},
generateScopedName: isProd
? '[hash:base64]'
: "[path]___[name]__[local]___[hash:base64:5]",
webpackHotModuleReloading: isProd ? false : true,
exclude: "node_modules",
handleMissingStyleName: isProd ? "throw" : "warn",
autoResolveMultipleImports: true,
},
];
}
module.exports = function (api) {
api.cache(true)
return {
plugins: ["@babel/transform-react-jsx", createReactCssModulesPlugin()],
};
};