Difference between revisions of "TypeScript"

From Organic Design wiki
m (Configuration: Fix closing source tag.)
m (ts-node: Add shebang.)
 
Line 22: Line 22:
 
== ts-node ==
 
== 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.
 
'''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.
 +
 +
<source lang="javascript">
 +
#!/usr/bin/env ts-node
 +
</source>
  
 
== SWC ==
 
== SWC ==

Latest revision as of 01:12, 5 September 2022

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
	}
}