I had generated tsconfig.json with tsc --init
,
and then I wrote react code in a .tsx file and got the error Cannot use JSX unless the '--jsx' flag is provided
I stumbled upon this jsx
setting of tsconfig
it has jsx
in commented mode as // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react', 'react-jsx'. */
so what do those three options mean? namely preserve
, react-native
and react
The presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project.
When input files are specified on the command line, tsconfig.json files are ignored. Depending on the JavaScript runtime environment which you intend to run your code in, there may be a base configuration which you can use at github.com/tsconfig/bases .
If no "files" property is present in a tsconfig.json, the compiler defaults to including all TypeScript (*.ts or *.tsx) files in the containing directory and subdirectories. When a "files" property is present, only the specified files are included.
The tsconfig.json file specifies the root files and the compiler options required to compile the project. By invoking tsc with no input files, in which case the compiler searches for the tsconfig.json file starting in the current directory and continuing up the parent directory chain.
jsx
property allows us to use .tsx files in the project
So following are two steps of using React with Typescript
1.Name your files with a .tsx extension
2.Enable the jsx option
TypeScript ships with three JSX modes: preserve, react, and react-native.
These modes only affect the emit stage - type checking is unaffected.
The preserve
mode will keep the JSX as part of the output to be further consumed by another transform step (e.g. Babel). Additionally, the output will have a .jsx file extension.
The react
mode will emit React.createElement, does not need to go through a JSX transformation before use, and the output will have a .js file extension.
The react-native
mode is the equivalent of preserve in that it keeps all JSX, but the output will instead have a .js file extension.react-jsx
(relevant for React 17) mode helps you to avoid the necessity of importing React in every file where jsx is used, i.e. it will emit
React has introduced a new JSX transform with the release of React 17 which automatically transforms JSX without using React.createElement. This allows us to not import React, however, you'll need to import React to use Hooks and other exports that React provides https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
https://www.typescriptlang.org/docs/handbook/jsx.html#basic-usage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With