1.3. Working with the TypeScript compiler

After installing TypeScript via npm, we will be able to use the TypeScript compiler command line interface.

Getting ready

Previous recipe, ‘Setting up your TypeScript development environment’ is a pre-requisite to configure TypeScript compiler options for TypeScript development.

How to do it…

  1. You can use the –init option in combination with any compilation flag to generate the initial tsconfig.json file:
    $ tsc --init --module amd foo.ts
    
  2. The preceding command will generate the following tsconfig.json file:
    {
      "compilerOptions": {
       "module": "amd",
       "target": "es3",
       "noImplicitAny": false,
       "outDir": "built",
       "rootDir": ".",
       "sourceMap": false
      },
      "exclude": [
       "node_modules"
      ],
      "files": [
       "foo.ts"
      ]
    }
    
  3. Once you have created a tsconfig.json file you can use the --project flag to indicate all the compilation flags:
    $ tsc --project
    

    Note that you must execute the preceding command from a folder that contains a tsconfig.json file.

How it works…

These compiler options can be passed through the console’s standard input (as we did in the previous example) or using a file named tsconfig.json. The following is an example of tsconfig.json file:

{
  "compilerOptions": {
   "target": "es5",
   "module": "commonjs",
   "moduleResolution": "node",
   "isolatedModules": false,
   "jsx": "react",
   "experimentalDecorators": true,
   "emitDecoratorMetadata": true,
   "declaration": false,
   "noImplicitAny": false,
   "removeComments": true,
   "noLib": false,
   "preserveConstEnums": true,
   "suppressImplicitAnyIndexErrors": true
  }
}

As you can see the previous tsconfig.json example contains multiple compilation options, passing all these options using the console’s standard input can become a really repetitive and time consuming tasks for that reason it is recommended to use a tsconfig.json file.

There’s more…

The TypeScript compiler allows us to use some flags to configure the compilation process. For example, we can use the --outFile compilation flag to specify the name of the file that will contain the generated JavaScript output.

$ tsc hello_world.ts --outFile hello_world.js

** There are many compilation flags available. For details, please refer to https://www.typescriptlang.org/docs/handbook/compiler-options.html. You will have an opportunity to put in practice some of the compilation flags through the examples in this book.**

See also


Shiv Kushwaha

Author/Programmer