使用`Emotion v11`的正确姿势 `Emotion css Prop`配置指南

862 阅读1分钟

使用Emotion v11的正确姿势 Emotion css Prop配置指南

须知

本指南基于 Emotion v11

使用Emotion的原因无非是看上了它独有的css Prop语法,相较于传统的styled语法,可以省略包装组件的步骤,减少代码量,利于调试。但Emotion底层使用了Babel来完成对jsx的扩展,并不是开箱即用的,下面是如何配置css Prop的指南。

步骤

1. 下载依赖

yarn add @emotion/react

2. 配置Babel

修改.babelrc文件并添加以下内容

  • 旧版本
{
  "presets": ["@emotion/babel-preset-css-prop"]
}
  • React版本>=16.14.0
{
  "presets": [
    [
      "@babel/preset-react",
      { "runtime": "automatic", "importSource": "@emotion/react" }
    ]
  ],
  "plugins": ["@emotion/babel-plugin"]
}
  • Next.js一起使用时
{
  "presets": [
    [
      "next/babel",
      {
        "preset-react": {
          "runtime": "automatic",
          "importSource": "@emotion/react"
        }
      }
    ]
  ],
  "plugins": ["@emotion/babel-plugin"]
}

.babelrc不可以时

使用create react app构架的项目默认时不暴露.babelrc文件的,使用craco解决这个问题。

修改craco.config.js并添加以下内容

仅演示React版本>=16.14.0的情况,其他情况自行变更

module.exports = {
  babel: {
    presets: [
      [
        "@babel/preset-react",
        { "runtime": "automatic", "importSource": "@emotion/react" }
      ]
    ],
    plugins: ["@emotion/babel-plugin"]
  }
}

使用

import { css } from '@emotion/react'

const style = css`
  display: flex;
`

const BaseHeader = () => {
  return (
    <div className="header" css={ style }>
    </div>
  )
}