Learn how to set up your first TypeScript project from scratch in just a few steps.
Step 1: Installing TypeScript
Before using TypeScript on your system, you must install the TypeScript compiler globally.
Run the following command to install TypeScript globally:
npm install -g typescript
Step 2: Setting Up Your Project
To set up your TypeScript project, start by creating an empty project directory in any IDE of your choice.
This command will create an index.js file inside the same directory your index.ts file resides.
This behavior may be undesirable as it would make your project hard to manage with multiple .js and .ts files in the same directory.
You change this default behavior and modify the behavior of your TypeScript compiler using the tsconfig.json file.
Run the following command in your terminal to create a tsconfig.json file in your project:
This generates a file containing all the configuration settings for your TypeScript compiler.
You’ll cover only the basics needed to start your project here, but you can learn more about it in the TypeScript tsconfig documentation.
Step 3: Setting Up the TypeScript Compiler for a Better Workflow
The tsconfig.json file contains configuration options for the TypeScript compiler divided into seven sections:
Most of the properties are disabled by default (they’re commented out). You can activate and modify them by un-commenting them.
- Open tsconfig.json and locate the emit section.
- In the emit section, un-comment the outDir property and specify the directory you want to store the compiled .ts files. Now anytime you run tsc, your .js files will be in the specified folder.
Running tsc followed by the name of the file you want to compile is not optimal for your workflow, especially when you need to compile multiple files.
To solve this problem, the TypeScript compiler provides a property that allows it to compile all the files in a directory in one command.
Follow these steps to set this up:
- Open tsconfig.json and locate the modules section.
- In the modules section, un-comment the rootDir property or rootDirs (if you want the compiler to compile multiple .ts directories into .js) and specify the file directory(s).
These settings will make your workflow better and your files easier to maintain.
The Advantages of TypeScript
Read the full article here