最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use TypeScript's transpile function with JSXTSX - Stack Overflow

programmeradmin2浏览0评论

Let's say I have a TypeScript 1.6 file containing this one single line that contains JSX (TSX):

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

When I pile this on the mand line with TypeScript 1.6 (installed via the ntypescript npm package):

ntsc --jsx react test.tsx

It produces the expected output:

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

However, when I try to do the same thing with the TypeScript JS API, I can't get it to work. I run node and then run these mands:

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

The result I get is:

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

Also, d is an empty array, so no diagnostic messages (i.e errors) were reported. What gives?

Let's say I have a TypeScript 1.6 file containing this one single line that contains JSX (TSX):

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

When I pile this on the mand line with TypeScript 1.6 (installed via the ntypescript npm package):

ntsc --jsx react test.tsx

It produces the expected output:

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

However, when I try to do the same thing with the TypeScript JS API, I can't get it to work. I run node and then run these mands:

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

The result I get is:

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

Also, d is an empty array, so no diagnostic messages (i.e errors) were reported. What gives?

Share Improve this question edited May 6, 2021 at 20:11 Johannes Fahrenkrug asked Aug 7, 2015 at 14:32 Johannes FahrenkrugJohannes Fahrenkrug 44.9k20 gold badges133 silver badges174 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

It turns out that I had to pass in ts.JsxEmit.React (which resolves to the number 2) instead of the string 'react' and then everything works.

So this is the working code:

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

Output:

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

Enjoy!

发布评论

评论列表(0)

  1. 暂无评论