TypeScript Compiler: How To?
Welcome to the second article in my Learn to TypeScript series. Today I will be discussing the TypeScript compiler and how we can use it to customize our development experience. To get your TypeScript environment set up we will need to do a couple things. Right off the bat, while we’re working we need to run the compiler, pointed at a specific file, everytime we want to compile our code. While this may be fine on a small project, it would be much more efficient if we could tell TypeScript to compile after every change we make.
Enter watch mode! With this handy feature, we can tell TypeScript to constantly listen for changes and, upon change, recompile our code. To set up watch mode, we can initialize our project as a TypeScript project by running:
tsc — init
This will then create a tsconfig.json file. Inside this file we find all of the options that the compiler comes with. Over the next few minutes I will discuss the options I use to help increase my productivity and effectiveness while using TypeScript.
There are a couple of options that we can add ourselves, after the main configuration object.
‘exclude’ array, contains files that we do NOT want to be compiled.
‘include’ array, you may have guessed, contains any files or folders that we want to be compiled.
‘files’ array, is similar to include, but we can not put folders in here, only files.
Now let’s move on to the built in compiler options, starting with target. The target property lets us choose which version of ECMAscript we want to use. This can be useful if we know our application will be run on older browsers like IE.
‘lib’ - this allows us to denote which default version and features TypeScript knows about. If you enter the value and hit ‘ctrl + space’, the auto complete box will pop up, showing you what options are available.
‘rootDir’ - this option sets where we keep our TS files
‘ourDir’- this sets where our output JS files will be stored
We can use these options together to keep our project structure clean and organized. Having our input and output files in separate directories is very useful on larger projects.
‘removeComments'-you guessed it, this removes comments from the output JS files.
‘noEmit’ — when this option is set to true, TypeScript will check for errors, but will not generate a JS file. This can be helpful with large files where we want to debug before compiling.
‘noEmitOnError’ — similar to the previous property, but with this option, as long as there are no errors, it will compile. However, if TypeScript does find an error, no files will be compiled.
There are more options to cover, but they are for more advanced situations. The properties covered in this article will help you customize your TypeScript experience and help make your code bulletproof! I hope you enjoyed the article and learned something along the way. I will be back next week with another article on TypeScript. Until then, happy coding!