网站搜索

reactjs - TypeScript:tsc 将 jsx 转译成比 babel 更冗长的代码


给定以下 JSX 代码片段:

<Typography variant={ "subtitle2" }>
    { props.text }
</Typography>

TypeScript 转译器 tsc 输出

_jsx(
    Typography, 
    Object.assign(
        { variant: "subtitle2" }, 
        { children: props.text }
    ), 
    void 0
)

而 babel 输出

_jsx(
    Typography, 
    { variant: "subtitle2", children: props.text }
)

不用说,tsc 的输出要详细得多,对于大型组件,它会产生更多的代码。

  • 为什么 tsc 会输出更详细的版本?
  • tsconfig.json 中有设置可以去掉这些额外的冗长信息吗?

当前,tsconfig.json具有以下相关设置:

{
    compilerOptions: {
        "jsx": "react-jsx",
        "target": "es6" // also tried "es2019"
        "module": "es6" // also tried "esnext"
    }
}

使用 babel 时,以下 .babelrc.json 已就位:

{
    "presets": [
        "@babel/preset-typescript",
        [
            "@babel/preset-react", {
                "runtime": "automatic"
            }
        ]
    ]
}

版本:

typescript: 4.2.4
@babel/core: 7.15.8
@babel/cli: 7.15.7
@babel/preset-typescript: 7.15.0
@babel/preset-react: 7.14.5