TypeScript

From Organic Design wiki
Revision as of 01:12, 5 September 2022 by Saul (talk | contribs) (ts-node: Add shebang.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Configuration

TypeScript configuration is done through the .tsconfig.json file in the root directory of your project. Your config file should look like the following:

{
	"compilerOptions": {
		"target": "es2022"
	},

	"include": [
		"./src/**/*.ts"
	],

	"exclude": [
		"node_modules"
	]
}

The target option is the ECMAScript version your source files are written in.

ts-node

ts-node is a variation of node that automatically compiles the TypeScript file to JavaScript before executing dropping the need to transpile the code first.

You should use its shebang where appropriate.

#!/usr/bin/env ts-node

SWC

SWC is a fast rust based compiler for TypeScript. To use the SWC compiler you need to add it to your project:

npm i --save-dev @swc/core

Then enable it in your TypeScript config:

{
	"ts-node": {
		"swc": true
	}
}

CJS

CommonJS is the default module system in TypeScript but if you want to set it explicitly you use the following settings in your TypeScript config:

{
	"compilerOptions": {
		"module": "commonjs"
	}
}

ESM

To make TypeScript transpile to ESM you need to specify a version ECMAScript that supports it in your TypeScript config:

{
	"compilerOptions": {
		"module": "es2022",
		"esModuleInterop": true
	}

	"ts-node": {
		"esm": true
	}
}