typescript-must-know
Setup
Setup is from https://basarat.gitbooks.io/
-
Setup a Node.js project package.json. Quick one :
npm init -y -
Add TypeScript (
npm install typescript --save-dev) -
Add node.d.ts (
npm install @types/node --save-dev) -
Init a
tsconfig.jsonfor TypeScript options (npx tsc --init) -
Make sure you have
compilerOptions.module:commonjsin yourtsconfig.json
Bonus: Live compile + run
Live compile part is from https://basarat.gitbooks.io/
- Add
ts-nodewhich we will use for live compile + run in node (npm install ts-node --save-dev) - Add
nodemonwhich will invokets-nodewhenever a file is changed (npm install nodemon --save-dev)
Now just add a script target to your package.json based on your application entry e.g. assuming its index.ts:
"scripts": {
"start": "npm run build:live",
"build:live": "nodemon --exec ./node_modules/.bin/ts-node -- ./index.ts"
},So you can now run npm start and as you edit index.ts:
- nodemon reruns its command (ts-node)
- ts-node transpiles automatically picking up tsconfig.json and the installed typescript version,
- ts-node runs the output javascript through Node.js.
Build JS file
$ npm run build