【问题标题】:How to use TypeScript's transpile function with JSX/TSX如何在 JSX/TSX 中使用 TypeScript 的 transpile 函数
【发布时间】:2015-10-31 01:10:00
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs typescript transpiler typescript1.6


    【解决方案1】:

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

    享受吧!

    【讨论】:

      猜你喜欢
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      • 2017-11-03
      • 2017-04-27
      • 1970-01-01
      • 2019-05-18
      相关资源
      最近更新 更多