There are a bunch of different ways that you can compile TypeScript and how you go about doing it will depend largely on what build tooling that you use. Since I'm using rollup
and babel
already to transpile my TypeScript code, I think it makes sense to utilize babel's typescript preset to handle all of our TypeScript compilation as well. So we will install it with npm i -D @babel/preset-typescript
and configure it in our rollup.config.js
.
Instructor: [0:00] The last thing that we need to do before we start writing TypeScript code is to configure our build tools to deal with that new code. I do want to note here that there are a bunch of different ways that you can compile TypeScript, and how you go about doing it will depend largely on what build tooling that you use.
[0:16] Since I am using Rollup in Babel already to transpile our code, I think it makes sense to utilize Babel's TypeScript preset to handle all of our TypeScript compilation as well. This will be a bit faster than processing it separately and should work well for our needs.
[0:32] I'm going to go ahead and install my needed dependency here, and that is the @babel/preset-typescript dependency. That's going to get the job done. Once that's installed, let's go ahead into our rollup.config and make the changes necessary to work with TypeScript.
[0:51] The first change I will make here is, I'm going to change our input file. Instead of main.js, I'm going to look for main.tsx, and we'll rename that file shortly.
[1:01] Tsx is the file extension that we need to use anytime that we're writing TypeScript with React's JSX syntax. It is very important. If you use JSX syntax, you have to use this tsx extension.
[1:13] The next thing that I'm going to do is configure my various Rollup plugins to also look for files with the .ts or .tsx file extensions. I'm going to configure both my node-resolve plugin and my Babel plugin to look for those as well.
[1:34] Then the last thing that I'll do is, I will add the preset that I just installed for Babel to handle all of our TypeScript code. I'm not going to override any options here. We'll run with the default options and save my file. Because we changed our entry point to main.tsx, I'm going to go ahead and rename that file so that it actually exists.
[2:01] Now, let's go ahead and run our dev script again to make sure everything works. Look at that. Everything still functions.