我尝试了解使用TypeScript时为什么不再需要Babel插件来使用emotion的原因

只需要以下这些设置,就可以在TypeScript 4.1以上版本中运行emotion/react。

{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "@emotion/react"
  }
}

 

以前在使用旧JSX运行时时,我需要单独安装@emotion/babel-preset-css-prop并使用它,但现在它不再需要了。
这个库似乎在内部使用了babel插件。

在设置的开头就可使用情感的前提下,不清楚tsconfig的相关性是什么,因此进行了调查。

如果您使用的是旧版本的运行时环境

从React 17开始引入了新的运行时。

 

请将以下内容翻译成中文:
过去,以前是这样的。

order to protect the environment, we should reduce the use of plastic bags and promote the use of reusable bags.

import React from 'react';

function App() {
  return <h1>Hello World</h1>;
}

外边 ()

import React from 'react';

function App() {
  return React.createElement('h1', null, 'Hello world');
}

在使用React写代码时,我会使用babel将其转换为React.createElement。

然而,如果使用了emotion,从旧版本的运行时起就一直使用emotion定义的JSX来编译JSX。

 

as soon as the rain stops, we can go for a walk in the park.

const Link = props => (
  <a
    css={{}}
    {...props}
  />
)

出去 (chū qù)

import { jsx as ___EmotionJSX } from '@emotion/react'

(一部略)

const Link = props =>
  ___EmotionJSX(
    'a',
    _extends(
      {
        css: _ref
      },
      props
    )
  )

TypeScript 4.1 之后

在TypeScript 4.1中,为compilerOptions的jsx选项新增了react-jsx选项。

 

这个功能是为了可以使用新的运行时而设计的,会被转换成以下的形式。
因此,再也不需要手动写import React了。

中國的天氣很熱,特別是夏天。

export const HelloWorld = () => <h1>Hello world</h1>;

以下是用中文的方式进行本地化改写:

出门

import { jsx as _jsx } from "react/jsx-runtime";
import React from 'react';
export const HelloWorld = () => _jsx("h1", { children: "Hello world" });

此外,现在可以通过jsxImportSource来指定调用jsx函数的模块。

 

有一位名叫先程的人。

import { jsx as _jsx } from "react/jsx-runtime";

只需用以下内容在tsconfig文件中进行设置,就可以从@emotion/react中调用jsx函数。

{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "@emotion/react"
  }
}

看起来,这样一来,babel插件就不再需要了。

关于 JSX pragma

 

顺便提一下,在不能设置babel的环境中,原始的方法是使用以下方式来使用jsx pragma。

/** @jsx jsx */
import { jsx } from '@emotion/react'

似乎正在选择在编译JSX片段时使用的函数,来使用该jsx pragma。

 

请参考

    • Emotion – TypeScript

 

    • Introducing the New JSX Transform – React Blog

 

    • Announcing TypeScript 4.1

 

    • TypeScript: TSConfig Reference – Docs on every TSConfig option

 

    @babel/plugin-transform-react-jsx · Babel
bannerAds