首页 > 解决方案 > 带有 TypeScript 的 create-react-app 中的样式化组件 babel 插件?

问题描述

我可以在使用 TypeScript 的 create-react-app 应用程序中使用样式化组件 babel 插件吗?

我在文档中读到有一个“宏 [that] 包含 [the] babel 插件的所有功能,同时允许未弹出的工具处理构建过程的 Babel 部分。”

我努力了:

npm install babel-plugin-macros

import styled from 'styled-components/macro';
const Div = styled.div`
`;

npm run start我得到的控制台上

Compiled with warnings.

./node_modules/babel-plugin-macros/dist/index.js
62:46-53 Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

./node_modules/babel-plugin-macros/node_modules/cosmiconfig/dist/loaders.js
8:17-34 Critical dependency: the request of a dependency is an expression

在浏览器中访问应用程序时,我得到

TypeError: __WEBPACK_IMPORTED_MODULE_1_styled_components_macro__.a.div is not a function

标签: typescriptstyled-components

解决方案


我遇到了同样的问题。我试图tsc -b -w在 monorepo 上运行(监视),同时在项目中运行react-scripts startcreate-react-app这样我就可以监视项目并在它们发生变化时构建上游项目。

我最终意识到这不起作用的原因是因为我在.ts文件而不是.tsx文件中定义了样式组件,例如Menu.styles.ts文件。当我将其重命名为Menu.styles.tsx并发手表时,+start工作始终如一。

希望这可以帮助某人。


推荐阅读