1

假设我有一个 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是一个空数组,因此没有报告诊断消息(即错误)。是什么赋予了?

4

1 回答 1

4

事实证明,我必须传入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));

享受!

于 2015-08-07T14:32:17.050 回答