This tutorial explores how we can build, structure, test and debug a Node.js application written in TypeScript. You can download the source code here.
Prerequisites
Install Node.js
Install VS Code
Getting TypeScript
TypeScript itself is simple to add to any project with npm
.
1 2 |
npm install -D typescript |
If you’re using VS Code then you’re good to go! VS Code will detect and use the TypeScript version you have installed in your node_modules
folder. For other editors, make sure you have the corresponding TypeScript plugin.
Create App Folder and package.json file
Create a new folder ‘TypeScript-NodeJS-Express-Seed’ and open the folder in command prompt.
Create a new node project using npm init command.
This will create a package.json file in the app folder.
Configure TypeScript for the project
You can pass options to the TypeScript compiler by either by using the CLI, or a special file called tsconfig.json
. By using this configuration file, we are telling TypeScript things like the build target (can be ES5, ES6, and ES7 at the time of this writing), what module system to expect, where to put the build JavaScript files, or whether it should create source-maps as well.
Add a new file ‘tsconfig.json’ in the folder ‘TypeScript-NodeJS-Express-Seed’ and add below contents into it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
{ "compilerOptions": { "module": "commonjs", "target": "es6", "noImplicitAny": true, "moduleResolution": "node", "sourceMap": true, "outDir": "dist", "baseUrl": ".", "paths": { "*": [ "node_modules/*", "src/types/*" ] } }, "include": [ "src/**/*" ] } |
compilerOptions | Description |
---|---|
"module": "commonjs" | The output module type (in your .js files). Node uses commonjs, so that is what we use |
"target": "es6" | The output language level. Node supports ES6, so we can target that here |
"noImplicitAny": true | Enables a stricter setting which throws errors when something has a default any value |
"moduleResolution": "node" | TypeScript attempts to mimic Node's module resolution strategy. |
"sourceMap": true | We want source maps to be output along side our JavaScript. See the debugging section |
"outDir": "dist" | Location to output .js files after compilation |
"baseUrl": "." | Part of configuring module resolution |
Install Packages
1 |
npm install express --save |
Install Typings
1 |
npm install @types/node @types/express --save-dev |
Project Structure
The project structure is as shown below.
Name | Description |
---|---|
dist | Contains the distributable (or output) from your TypeScript build. This is the code which we run. |
node_modules | Contains all your npm dependencies |
src | Contains your source code that will be compiled to the dist dir |
src/controllers | Controllers define functions that respond to various http requests |
src/models | Models that will be used in storing and retrieving data |
Create app.ts – Entry point of the app
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import * as express from 'express'; /** * Controllers (route handlers). */ import * as empController from "./controllers/employee-controller"; /** * Create Express server. */ const app = express(); /** * Express configuration. */ app.set("port", process.env.PORT || 3000); /** * Start Express server. */ app.listen(app.get("port"), () => { console.log((" App is running at http://localhost:%d in %s mode"), app.get("port"), app.get("env")); console.log(" Press CTRL-C to stop\n"); }); /** * Primary app routes. */ app.get("/GetEmployee", empController.getEmployee); module.exports = app; |
Create EmployeeController.ts in ‘src/controllers’ folder
1 2 3 4 5 6 7 8 9 |
import { Request, Response } from "express"; /** * GET / * Home page. */ export let getEmployee = (req: Request, res: Response) => { res.send("Received Get Employee Request.."); }; |
Compile and Run the App
Open command prompt and go the root folder of the app (HiveStoreAPI folder) and run the command tsc. This will compile the typescript files according to the typeconfig.json configuration. After compilation, the js files are generated in dist folder.
1 |
\TypeScript-NodeJS-Express-Seed>tsc |
Now go the ‘dist’ folder. Here you can see the trasnspiled code files.
Go to dist folder in command prompt and run the command ‘node app.js’
1 |
\TypeScript-NodeJS-Express-Seed\dist>node app.js |
Below is a snapshot of the commands and results.
Now open a browser and browse the url http://localhost:3000/GetEmployee.
The seed project is available in GitHub. You can download the source code here.
Great article that teaches us to create a Node/Typescript project in Code, from scratch. Nowadays rare are such articles that removes the mystery of opaque packages and scripts and allow us to wean off our dependency on such packages/scripts.
I had to fix a few lines though in order to make things work. These have to do with the ways imports are used. I had to add
esModuleInterop
to true, and the syntax of the import of defaults had to be changed. example,import express from "express"
.Thanks once again.