TypeScript with Node.js

    1. Setup a Node.js project . Quick one : npm init -y
    2. Add TypeScript (npm install typescript --save-dev)
    3. Add node.d.ts (npm install @types/node --save-dev)
    4. Init a tsconfig.json for TypeScript options (npx tsc --init)
    5. Make sure you have compilerOptions.module:commonjs in your tsconfig.json

    That’s it! Fire up your IDE (e.g. alm -o) and play around. Now you can use all the built in node modules (e.g. import fs = require('fs');) with all the safety and developer ergonomics of TypeScript!

    • Add ts-node which we will use for live compile + run in node (npm install ts-node --save-dev)
    • Add nodemon which will invoke ts-node whenever 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:

    • nodemon reruns its command (ts-node)
    • ts-node transpiles automatically picking up tsconfig.json and the installed typescript version,

    Using modules written in TypeScript is super fun as you get great compile time safety and autocomplete (essentially executable documentation).

    Creating a high quality TypeScript module is simple. Assume the following desired folder structure for your package:

    1. package
    2. ├─ package.json
    3. ├─ tsconfig.json
    4. ├─ src
    5. ├─ All your source files
    6. ├─ index.ts
    7. ├─ foo.ts
    8. └─ ...
    9. └─ lib
    10. ├─ All your compiled files
    11. ├─ index.d.ts
    12. ├─ foo.d.ts
    13. ├─ foo.js
    14. └─ ...
    • In your tsconfig.json

      • have : "outDir": "lib" and "declaration": true < This generates declaration and js files in the lib folder
      • have include: ["./src/**/*"] < This includes all the files from the src dir.
      • "main": "lib/index" < This tells Node.js to load lib/index.js
      • "types": "lib/index" < This tells TypeScript to load lib/index.d.ts

    Example package:

    • npm install typestyle for TypeStyle
    • Usage: import { style } from 'typestyle'; will be completely type safe.

    MORE:

    • If you package depends on other TypeScript authored packages, put them in dependencies/devDependencies/peerDependencies just like you would with raw JS packages.

    Such NPM modules work just fine with browserify (using tsify) or webpack (using ts-loader).