如何在使用 TypeScript 的 create-react-app 中使用带有 babel 插件的样式组件?

How to use styled components with babel plugin in create-react-app that uses TypeScript?

我已阅读有关样式化组件工具的文档。我已经能够在没有 babel 插件的情况下使用样式组件,但是我无法通过 babel 插件使用样式组件。通过阅读文档,我的印象是我最好的选择是使用样式化组件宏。

我的项目使用

我安装了以下软件包:

  "dependencies": {
    "styled-components": "^4.0.0"
  },
  "devDependencies": {
    "@types/styled-components": "^4.0.1",
    "babel-plugin-macros": "^2.4.2",
    "babel-plugin-styled-components": "^1.8.0"
  },

这里我在 .tsx 文件中使用样式组件:

import styled from 'styled-components/macro';

不幸的是我得到这个错误:

[ts] Could not find a declaration file for module 'styled-components/macro'. '/Users/.../styled-components/dist/styled-components-macro.cjs.js' implicitly has an 'any' type.

我可以通过删除导入语句的 /macro 部分来让它工作,但据我所知,我在调试过程中错过了更具可读性的 class 名称。

您可以通过将以下代码添加到项目中的 .d.ts 文件(而不是在另一个模块中)来声明 styled-components/macro 模块具有 API 与 styled-components 相同):

declare module "styled-components/macro" {
    export * from "styled-components";
    import styled from "styled-components";
    export default styled;
}

考虑在对 DefinitelyTyped 的拉取请求中提出此声明(以正确的格式:在那里你需要一个单独的 macro.d.ts 文件而不是使用 declare module),也许 @types/styled-components 维护者会知道它是否完全准确。