如何使用 TypeScript 的转译函数 JSX/TSX

How to use TypeScript's transpile function with JSX/TSX

假设我有一个 TypeScript 1.6 文件包含这一行,其中包含 JSX (TSX):

var a = (<div></div>);

当我使用 TypeScript 1.6(通过 ntypescript npm 包安装)在命令行上编译时:

ntsc --jsx react test.tsx

它产生了预期的输出:

more test.js
var a = (React.createElement("div", null));

但是,当我尝试使用 TypeScript JS API 做同样的事情时,我无法让它工作。我 运行 node 然后 运行 这些命令:

var ts = require('ntypescript');
src = 'var a = (<div></div>);'
d = []; // for diagnostics
compilerOptions =  {jsx: 'react', module: ts.ModuleKind.CommonJS};
res =  ts.transpile(src, compilerOptions, 'test.tsx', d);

我得到的结果是:

'var a = (<div></div>);\n'

此外,d 是一个空数组,因此没有报告任何诊断消息(即错误)。给出了什么?

事实证明,我必须传入 ts.JsxEmit.React(解析为数字 2)而不是字符串 'react',然后一切正常。

所以这是工作代码:

var ts = require('ntypescript');
src = 'var a = (<div></div>);'
d = []; // for diagnostics
compilerOptions =  {jsx: ts.JsxEmit.React, module: ts.ModuleKind.CommonJS};
res =  ts.transpile(src, compilerOptions, 'test.tsx', d);

输出:

var a = (React.createElement("div", null));

尽情享受吧!