从自定义TS文件重新导出styled-components/macro无法生效怎么解决
问题根因
styled-components/macro 基于 Babel 宏实现,仅会在编译阶段识别直接从 styled-components/macro 包导入的标识符。你将其封装到自定义custom-styled.ts后,宏在编译扫描时无法识别二次导出的styled属于宏处理范围,因此不会注入调试类名、编译优化等特性,自然无法达到预期效果。
另外你当前代码里的css/createGlobalStyle等API都是从普通styled-components包导出的,即使styled能正常运行,这些API也不会具备macro的相关特性。
修复方案
方案1:类型重定义+直接导入macro(最稳定,推荐)
你封装自定义文件的核心诉求大概率是给styled-components绑定自定义的Theme类型,不需要二次导出macro,直接做类型重定义即可:
- 新建类型声明文件
styled.d.ts放在项目src目录下:
import 'styled-components' import { ThemeInterface } from './theme' declare module 'styled-components' { export interface DefaultTheme extends ThemeInterface {} }
- 删掉原来的
custom-styled.ts,所有需要用macro的地方直接从styled-components/macro导入即可。此时所有API都会自动带上你自定义的Theme类型,同时完整保留macro的所有特性:
// App.tsx 示例 import styled, { css, createGlobalStyle } from 'styled-components/macro' // 此时styled已经自带ThemeInterface类型提示,不需要再从自定义文件导入
方案2:配置babel宏识别自定义导出(适合必须保留封装结构的场景)
如果一定要保留custom-styled.ts的封装结构,需要修改babel-plugin-macros的配置,让它识别你二次导出的标识符属于styled-components宏的处理范围:
- 首先修正
custom-styled.ts的导出,所有API都从macro导入后再做类型断言:
import styled, { css, createGlobalStyle, keyframes, ThemeProvider, withTheme } from 'styled-components/macro' import type { ThemedStyledComponentsModule } from 'styled-components' import { ThemeInterface } from './theme' const typedStyled = styled as ThemedStyledComponentsModule<ThemeInterface>['default'] const typedCss = css as ThemedStyledComponentsModule<ThemeInterface>['css'] const typedCreateGlobalStyle = createGlobalStyle as ThemedStyledComponentsModule<ThemeInterface>['createGlobalStyle'] const typedKeyframes = keyframes as ThemedStyledComponentsModule<ThemeInterface>['keyframes'] const typedThemeProvider = ThemeProvider as ThemedStyledComponentsModule<ThemeInterface>['ThemeProvider'] const typedWithTheme = withTheme as ThemedStyledComponentsModule<ThemeInterface>['withTheme'] export { typedCss as css, typedCreateGlobalStyle as createGlobalStyle, typedKeyframes as keyframes, typedThemeProvider as ThemeProvider, typedWithTheme as withTheme } export default typedStyled
- 修改你项目的babel配置(
babel.config.json或者.babelrc),给babel-plugin-macros增加识别规则:
{ "plugins": [ ["macros", { "styled-components": { "imports": [ { "module": "./custom-styled" }, { "module": "./custom-styled", "export": "css" }, { "module": "./custom-styled", "export": "createGlobalStyle" }, { "module": "./custom-styled", "export": "keyframes" } ] } }] ] }
配置完成后重启项目即可生效,所有从custom-styled.ts导入的API都会正常触发styled-components宏的处理逻辑。
内容的提问来源于stack exchange,提问作者Jasurbek Nabijonov
相关产品推荐
相关产品推荐

