引入wix-style-react后编译报错:export未找到问题求助
解决wix-style-react在Create React App中编译失败的问题
问题原因
wix-style-react内部使用Stylus CSS Modules时,采用了命名导出st对象的方式,但Create React App 5(react-scripts@5.x)默认的css-loader配置仅启用了CSS Modules的默认导出,未开启命名导出支持,导致编译时找不到st导出,出现类似如下错误:
ERROR in ./node_modules/wix-style-react/dist/es/src/SkeletonRectangle/SkeletonRectangle.js 43:19-21 export 'st' (imported as 'st') was not found in './SkeletonRectangle.st.css' (possible exports: default)
解决方案
方案1:使用react-app-rewired修改配置(无需eject)
这是最推荐的方式,无需暴露Create React App的核心配置:
- 安装依赖:
npm install react-app-rewired customize-cra --save-dev
- 在项目根目录创建
config-overrides.js文件,添加以下配置:
const { override, adjustStyleLoaders } = require('customize-cra'); module.exports = override( adjustStyleLoaders(loaders => { if (loaders.modules) { // 开启CSS Modules的命名导出支持 loaders.modules.namedExport = true; } }) );
- 修改
package.json中的scripts命令,替换react-scripts为react-app-rewired:
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" }
- 重启项目:
npm start
方案2:eject后手动修改webpack配置
如果你不介意暴露Create React App的配置,可以选择eject后修改:
- 执行eject命令(此操作不可逆):
npm run eject
- 打开
config/webpack.config.js,找到处理CSS Modules的规则(搜索modules: {),将namedExport设置为true:
// 找到类似如下的配置块 modules: { localIdentName: isEnvProduction ? '[hash:base64:8]' : '[path][name]__[local]--[hash:base64:5]', // 添加或修改这一行 namedExport: true, }
- 重启项目即可。
验证
修改配置后,重新引入wix-style-react的组件(比如import { Button } from 'wix-style-react'),编译应该能正常通过。
内容的提问来源于stack exchange,提问作者user2235692
相关产品推荐
相关产品推荐

