Configuring TypeScript 17 exercises
solution

Update tsconfig.json to Support JSX

We need to add the jsx option to our tsconfig.json file to tell TypeScript how to handle JSX syntax.

The jsx option has five possible values, but we'll focus on three: preserve, react, and react-jsx.

preserve

When jsx is set to preserve, TypeScript leaves the JSX syntax as it

Loading solution

Transcript

00:00 So, the thing we need to do is to go into our tsconfig.json and add a JSX flag. JSX has five different possible values. The ones we need to know about are, first of all, preserve. Now, preserve is kind of weird, because what preserve will do is it will say,

00:15 OK, great, you're using TSX. I'm going to just preserve the JSX as it is and do nothing to it. In fact, I'm going to create a .jsx file. Ignore this .js. If I run this again and just delete the whole dist folder, then it will just basically create a dist containing a JSX file.

00:34 So, dist index.jsx, and it does nothing to this div here. Interesting. But that's not always what we want, especially if we're bundling for a library or something, and we want this actually to be transformed into actual JavaScript instead of JSX files.

00:51 So, another approach is we could do react. Now, what react does is it will give us a .js file instead. So, ignore this .jsx file. This JS file is actually what's produced, and it says return react.createElement here. Now, this is weird, because we're not actually importing react here.

01:10 So, you might get some weird errors in here saying react refers to a UMD global. Now, if we say import react from react, this error is actually going to go away, because we're now importing react, and it's actually in scope. So, doing it this way forces you to add react or import react from that setup.

01:29 So, another way to do it is to say react.jsx. When we say react.jsx, this is for sort of very, I think, modern versions of react. I can't remember whether it was 17 or 18 this came in. But this one means you don't need to import react,

01:44 and you actually just get to say import JSX as JSX from react.jsx.runtime. Lovely. This means that you don't need to import it, and it imports a more modern JSX transform that you can then use.

01:58 So, this is the version that I would suggest you use if you're bundling this into a library, which is then going to be imported by other people. If you're distributing it to NPM, I would suggest using react.jsx. That's going to give you the best behavior.

02:13 And I think, in general, this is probably where you want to be with setting your JSX option. There are some niche cases where you want to say preserve, and preserve is usually a good default when you're not bundling it yourself with TSC. But when you're bundling with TSC, you want this setting because it works nicely.