@emotion/react + typescript + react函数组件 + craco

516 阅读1分钟

github:github.com/emotion-js/…

  1. 安装@emotion/react
npm install --save @emotion/react
  1. craco.config.js中配置babel(参考:github.com/emotion-js/…
module.exports = {
    babel: {
        "presets": [
            [
                "@babel/preset-react",
                { "runtime": "automatic", "importSource": "@emotion/react" }
            ]
        ],
        "plugins": ["@emotion/babel-plugin"]
    },
}

否则在函数组件中使用会报如下错误(在emotion的github仓库中搜索classic,找到的解决方案)

/** @jsxImportSource @emotion/react */

# Error: importSource cannot be set when runtime is classic.
  1. 配置tsconfig.json(参考:github.com/emotion-js/…
"compilerOptions": {
    "types": ["@emotion/react/types/css-prop"]
  }

否则如下错误:

Property 'css' does not exist
  1. 添加 index.d.ts
import { DOMAttributes } from "react"

declare namespace React {
 interface HTMLAttributes<T> extends DOMAttributes<T> {
   css?: any;
 }
}

否则编辑器会报如下错误:

# Property 'css' does not exist on type 'DetailedHTMLProps'
  1. 安装vscode-styled-components插件提供高亮和语法提示