Typescript compiler options target and module| tsconfig.json compiler options

This tutorial explains typescript compiler target and module options configuration.

You can also check how to generate tsconfig.json file and typescript tsconfig.json

tsconfig.json provides compilerOptions section to configure Compiler options for typescript. target and module are options in compilerOptions sections.

What is the target option in tsconfig used for?

target is an option used to select the javascript(ECMAScript) version used for generating javascript code from Typescript code.

Based on the ECMAScript Version in the target option, Syntaxes and features support generated Javascript

{
  "compilerOptions: {
    "target":"<ECMAScript-Version>"
  }
}

Following are values for ECMAScript-Version

  • es3(ECMAScript 3) is a default option, Supports old browsers
  • es5(ECMAScript 5)
  • es6(“es2015”: ECMAScript 2015)
  • es2016
  • es2017
  • es2018
  • es2019
  • es2020
  • es2021
  • es2022
  • es2023
  • es2024
  • ESNext : It tells to use the standard latest ECMAScript Version, not have support in all browsers or environments.

Generated Javascript code contains features available in mentioned in the target.

For example, if you have an arrow function code in typescript ()=> "str".

target:es5: arrow functions are not supported in ES5, So generate a javascript as functional expression function(){return "str"}. target:es6: ES6 supports this, JS contains a code as ()=> "str"

What is the module option in tsconfig used for?

The module option in tsconfig.json tells to typescript compiler to pick the javascript syntax used for modules when compiled to javascript.

This option determines how to organize and generate module structure in javascript

{
  "compilerOptions: {
    "module": "options",
  }
}

Possible valid values:

  • commonjs(CommonJS (Node.js)) Uses required and module.export.
  • AMD (Asynchronous Module Definition)
  • umd (Universal Module Definition)
  • system (SystemJS)
  • es6 or es2015(ECMAScript 2015): native modules that support import and export
  • ESNext: Latest module syntax feature supports

For example, if you set the module to commonjs,

The module syntax used in generate javascript code is required, and module.export for import,export

var x = required("module");
module.exports = { module1, module2 };

if you set the module to es2015, The syntax used for the module is import/export

Module and target examples for browsers and Nodejs

For Browsers and Nodejs. If your application runs on browsers, You need to set the below configuration


 {
  "compilerOptions": {
    "target": "es6",
    "module": "es2015"
  }
}

In the above configuration, the target uses es6 and the module is es2015, which applies to the latest modern browsers, and supports native module loading syntax.

If your application does not support it fully, Then use the module with commonjs