Mastering TypeScript 3
上QQ阅读APP看书,第一时间看更新

Creating a tsconfig.json file

The TypeScript compiler uses a tsconfig.json file at the root of the project directory to specify any global TypeScript project settings and compiler options. This means that instead of compiling our TypeScript files one by one (by specifying each file on the command line), we can simply type tsc from the project root directory, and TypeScript will recursively find and compile all TypeScript files within the root directory and all sub-directories. The tsconfig.json file that TypeScript needs in order to do this can be created from the command line by simply typing the following:

tsc --init

The result of this command is a basic tsconfig.json file as follows:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "strict": true,
        "esModuleInterop": true
    }
}

This is a simple JSON format file, with a single JSON property named compilerOptions, which specifies compile options for the project. The target property indicates the preferred JavaScript output to generate, and can be either es3, es5, es6, ES2016, ES2017, or ESNext. The option named strict is a flag to turn on all strict type-checking options. We will explore the meaning of these options in Chapter 5, Declaration Files and Strict Compilation Options. The esModuleInterop option has to do with the generation of modules, which we will also discuss in Chapter 10, Modularization.

TypeScript allows for multiple tsconfig.json files within a directory structure. This allows different sub directories to use different compiler options.

With our tsconfig.json file in place, we can compile our application by simply typing the following:

tsc

This command will invoke the TypeScript compiler, using the tsconfig.json file that we have created, and generate a hello.js JavaScript file. In fact, any TypeScript source file that has a file extension of .ts will generate a JavaScript file with an extension of .js.

We have successfully created a simple Node-based TypeScript development environment, with a simple text editor and access to the command line.