Skip to content

Latest commit

 

History

History
93 lines (74 loc) · 1.84 KB

setup-a-nodejs-project-with-typescript.md

File metadata and controls

93 lines (74 loc) · 1.84 KB

Setup A Nodejs Project With TypeScript

Category: Nodejs

This TIL will setup a Node project with TypeScript running Express on port 3000.

The application will watch for changes in code to trigger a TypeScript compilation then use nodemon to automatically reload JavaScript code.

mkdir my-node-project

Run yarn init and follow the prompts

yarn init
[follow prompts...]

Install TypeScript dev dependency

yarn add -D typescript

Initialise TypeScript

npx tsc --init

Install other dev dependencies

yarn add -D rimraf nodemon npm-run-all

Install Express

yarn add -D express @types/express

Configure package.json

"scripts": {
    "clean": "rimraf dist",
    "build": "tsc",
    "watch:build": "tsc --watch",
    "watch:server": "nodemon './dist/index.js' --watch './dist'",
    "start": "npm-run-all clean build --parallel watch:build watch:server --print-label"
}

Configure tsconfig.json

{
  "compilerOptions": {
    "target": "es5",       
    "module": "commonjs",  
    "strict": true,
    "esModuleInterop": true, 
    "skipLibCheck": true,                     
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist",    
  },
  "include": ["./src/**/*"],
  "exclude": [
    "node_modules"
  ]
}

Create src/index.ts file

import express = require('express');

const app: express.Application = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Listening on port 3000');
});

Start the server

yarn start

Browse to http://localhost:3000

Any changes you make to source files should be automatically recompiled and visible by refreshing the browser.

See TypeScript in 5 minutes for more details.