DEV Community

miku86
miku86

Posted on

TypeScript: Setting Up Our Compiler

Intro

In the last article, we talked about the basic workflow when writing in TypeScript.

In today's article, we will learn how to configure the TypeScript compiler.


Overview

Our configuration can be made in a file named tsconfig.json or at the command line.

For this article, we use tsconfig.json.

If we don't have a tsconfig.json, we have to use tsc [filename] to compile.

If we do have a tsconfig.json, we have to use tsc to compile, tsc [filename] would ignore the tsconfig.json


Create a tsconfig.json

We can use tsc --init to get a default tsconfig.json.

This is awesome, because the created tsconfig.json has a lot of useful compilerOptions in it, including comments.

{
  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    ...
}
Enter fullscreen mode Exit fullscreen mode

Below the compilerOptions, you can also modify files, include, exclude, compileOnSave and extends.

Most of the time I use:

"exclude":[
  "node_modules",
  "build"
]
Enter fullscreen mode Exit fullscreen mode

Basic Options

There are nearly 100 options, let's talk about some basic ones:

  • target: specify ECMAScript target version: es3 from 1999 is the default option, I use es2016, because it has all the new stuff like const and async/await, but isn't too new to break stuff.
  • declaration: generates a .d.ts, useful for publishing a package
  • sourceMap: generates a source map, useful for debugging, I use true.
  • outDir: output dir of compiled files, I use "./build"
  • removeComments: removes comments, I use true
  • strict: very useful - enable all strict type-checking options, these are the options that follow directly below. I use true
  • noUnusedParameters: reports unused parameters, I use true
  • noImplicitReturns: reports missing returns, I use true
  • allowSyntheticDefaultImports: allows default imports from modules with no default export, I use true
  • esModuleInterop: creates namespace objects for all imports, I use true

Next Part

We will learn how to write some basic code.


Further Reading

tsconfig.json Docs
TypeScript Compiler Options
my personal tsconfig.json

Top comments (0)