首页 > 解决方案 > 如何将 TSX 源代码转换为 TS 代码?

问题描述

本质上,我想要@babel/plugin-transform-react-jsx提供的行为,但保留所有类型、其他 TS 语言功能、ESNext 语法、注释等(我只是想转换 TypeScript XML 格式的代码使用指定的 JSX-factory 函数(例如React.createElement// jsxbring-your-own/等)转换成普通的 TypeScript

// in
let name: any = 'world';
const div = <div>hello {name as string}</div>;
// out (classic runtime)
let name: any = 'world';
const div = React.createElement('div', null, 'hello ', name as string);

// out (automatic runtime)
let name: any = 'world';
const div = _jsxs('div', { children: ['hello ', name as string] });

标签: reactjstypescriptbabeljstsx

解决方案


我认为你误解了打字稿使用的概念。我们仅在开发中使用 typescript 来实现基于模式的可靠方法。在运行 build 命令时,您的 typescript 代码会被转换为 javascript 代码,并且所有相关的 typescript 功能都会被删除。所以基本上我们在生产中运行 javascript。

我的理解是,您希望在编译打字稿代码时保留@babel/plugin-transform-react-jsx 提供的行为以及相应的打字稿类型。但是在我看来这是不可能的,因为 typescript 编译器只会将 typescript 代码转换为 js,而丢弃所有类型。


推荐阅读