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 compile this on the command 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 commands:
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);
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?
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
compilerOptions = {jsx: ts.JsxEmit.React, module: ts.ModuleKind.CommonJS};
res = ts.transpile(src, compilerOptions, 'test.tsx', d);
Output:
var a = (React.createElement("div", null));
Enjoy!