Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell Typescript compiler to compile JSX in .ts files?

I have some .ts files that has .jsx syntax in them. I want to tell tsc to compile my these .ts files like compiling .tsx files.

Is is possible to configure tsc to do that?

How can I configure vscode to support syntax highlighting for JSX syntax in these files?

like image 606
alisabzevari Avatar asked Oct 05 '16 09:10

alisabzevari


People also ask

Can we write JSX in ts file?

ts files still support the casting form which will cause conflicts if you'll have jsx code in them.

How do I convert TSX to JSX?

If just running tsc doesn't work, read this code.visualstudio.com/docs/typescript/typescript-compiling Effectively you can just compile it into Javascript. If the output of tsc is too much, just go through the tsx files and remove TS specific syntax, then rename to . jsx.

What is TypeScript JSX file?

A TSX file is a TypeScript (. TS) file written using JSX syntax. It contains code that is most likely part of a single-page or mobile application. TSX files can be opened in any text editor, but are meant to be opened in source code editors.

Does JSX need to be compiled?

React uses a special syntax that resembles HTML to declare components. This markup, called JSX, is embedded in the component JavaScript and needs to be compiled to JavaScript before it's usable by the browser.


1 Answers

No, you must have your react code in .tsx files, as the docs say:

In order to use JSX you must do two things.

  1. Name your files with a .tsx extension
  2. Enable the jsx option

The reason for this is that in typescript you cast in this form:

interface Point {
    x: number;
    y: number;
}

let p = <Point> {};

In tsx files however this is not possible because <Point> can be markup for a Point component.
Because of that in tsx files casting is not possible and you need to type assert:

let p = {} as Point;

But regular .ts files still support the casting form which will cause conflicts if you'll have jsx code in them.

like image 138
Nitzan Tomer Avatar answered Sep 21 '22 16:09

Nitzan Tomer