Most popular front-end frameworks like Nuxt or Angular already give you a TypeScript option when you first install them.
But what happens on the back-end? Say you want to build a server with Express running on Node.js, and you'd rather use TypeScript so the code stays structured and mostly bug-free.
Then you have to do the setup yourself. In this article we'll walk through setting up TypeScript with Node.js and Express in a relaxed, easy-to-follow way. Let's get started! ๐
Key takeaways
- TypeScript adds static typing and autocompletion, which makes code in Node.js safer and less bug-prone.
- The ts-node package runs TypeScript files directly, with no manual compile step during development.
- For production, TypeScript files must be compiled to plain JavaScript so performance stays optimal and Node.js compatible.
Preparation
Node.js + TypeScript + Express = ๐คฉ
Before we start coding, make sure these programs are installed on the computer:
- Node.js
- npm or yarn
If they're missing, head to the install Node.js guide and set them up first.
To be sure everything is installed correctly, run these commands in the terminal to check the versions.
Checking the Node.js version:
$ node -v
v14.16.0
Checking the npm version:
$ npm -v
7.15.0
If the terminal prints version numbers like the ones above, you're safe to move to the next step.
Initializing the Node.js Project
First, open the terminal, create a new folder for this project, and move into it.
mkdir typenode && cd typenode
After that, we initialize the package.json file with the npm init command.
npm init -y
Now let's build a simple server with Express in plain JavaScript first, to confirm everything runs normally. Create a new file named main.js in the project root directory and write the code below (feel free to copy it for speed, hehe):
const express = require("express");
function main(){
const app = express();
const port = 8080;
// simple endpoint to show the text 'Hello Express Node.js'
app.get("/", (req, res) => res.send("Hello Express Node.js"));
// start the express server
app.listen(port, () => {
console.log(`[server] server dimulai di http://localhost:${port} โก`);
});
}
main();
Before running the code, we obviously have to install the express library first so no error shows up.
npm install express # with npm
yarn add express # with yarn
Once the installation finishes, it's time to run that server.
node main.js
If it succeeds without trouble, you'll see a success message in the terminal:
[server] server dimulai di http://localhost:8080 โก
Open your favorite browser and visit http://localhost:8080 to see the result live. If the text shows up, congratulations. Next we'll start mixing in the TypeScript part.
Adding TypeScript to the Project
To start using TypeScript, we need two more main dependencies:
typescript: The core library that compiles TypeScript code into standard JavaScript that Node.js understands.ts-node: A very handy helper that lets us run TypeScript files directly in Node.js without manual compilation during development.
Run this command in the terminal to install both:
npm install typescript ts-node --save-dev # with npm
yarn add -D typescript ts-node # with yarn
As a note, the --save-dev flag on npm, or -D on yarn, puts these dependencies into devDependencies inside package.json. We only need these tools during development, so they don't need to reach production.
After the install finishes, we need a configuration file for the TypeScript compiler. Create a file named tsconfig.json in the project's root directory, then fill it with the configuration below:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es5",
"outDir": "build",
"rootDir": "src",
"baseUrl": ".",
"strict": true
}
}
So nothing feels confusing, here's a short explanation of those options:
module: Sets the module format of the compiled output. For server or back-end apps,commonjsis the safest standard choice.target: Sets the JavaScript version of the output. We pickes5here for compatibility with older runtime environments.outDir: The destination folder for compiled JavaScript files. We point it at thebuildfolder.rootDir: The main folder that holds all our TypeScript source files. We set it to thesrcfolder.baseUrl: The base path used to resolve non-relative module imports.
For full documentation on the other configuration options, head straight to the official tsconfig docs.
Next, we need to update the scripts section inside package.json to make running and building the app easier. Change the contents to look like this:
{
"name": "typenode",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc",
"serve": "node ./build/main.js",
"dev": "ts-node ./src/main.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"typescript": "^4.3.2",
"ts-node": "^10.0.0"
}
}
Building the Server with TypeScript
The configuration step is almost done! Before moving any code, we need two more packages that hold type definitions:
@types/node: Provides type definitions for built-in Node.js objects.@types/express: Provides type definitions for Express.
Run this command in the terminal to install them:
npm install @types/node @types/express --save-dev # with npm
yarn add -D @types/node @types/express # with yarn
Because TypeScript uses a static typing system, these type packages matter a lot. They let the compiler know which data types are legal on each object. The nice part: if you use Visual Studio Code, these packages switch on very capable code completion and IntelliSense. Writing code gets faster and better supported! ๐
Now let's tidy the directory structure. Create a new folder named src to hold all the TypeScript code we're going to write.
mkdir src
Once the folder exists, move the main.js file we made earlier into src, then change the extension to main.ts.
mv main.js src/main.ts
Your project structure should now look neat, like this:
.
โโโ tsconfig.json
โโโ src
โ โโโ main.ts
โโโ node_modules
โโโ package.json
โโโ package-lock.json
Open src/main.ts in the editor and rewrite the code with modern TypeScript syntax, like this:
import express from "express";
function main(){
const app = express();
const port = 8080;
// simple endpoint to show the text 'Hello Express TS'
app.get("/", (req, res) => res.send("Express + Typescript + NodeJS = ๐"));
// start the express server
app.listen(port, () => {
console.log(`[server] server dimulai di http://localhost:${port} โก`);
});
}
main();
Now it's time to try running this TypeScript app. Just run the following command in the terminal:
npm run dev
If the configuration is right, you'll see the same success output as before. Your server is now running on TypeScript behind the scenes! Remember, from here on, always keep new files inside the src folder.
Compiling TypeScript to JavaScript
After the fun of coding in TypeScript, one important step remains before publishing to production: compilation.
Node.js can't run TypeScript files directly by default. That's why every file in src has to become plain JavaScript so performance stays fast and optimal.
To run the compilation, use this command:
npm run build
Once the command finishes, you'll find a new folder named build containing main.js. The compiled file looks like this:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var express_1 = __importDefault(require("express"));
function main() {
var app = express_1.default();
var port = 8080;
// simple endpoint to show the text
app.get("/", function (req, res) { return res.send("Express + Typescript + NodeJS = ๐"); });
// start the express server
app.listen(port, function () {
console.log("[server] server dimulai di http://localhost:" + port + " โก");
});
}
main();
As you can see, modern syntax like arrow functions became plain functions (anonymous function), and variables became var. That's because we set the compiler target to es5 in tsconfig.json. If you want more modern output, change that target value to es6 or newer.
Finally, to run the compiled production code, use this command:
npm run serve
The Quick Version (TL;DR)
If you're in a hurry, or want to see the finished result without typing everything from scratch, relax. You can clone or copy the full code from the GitHub repository.
Once copied, just run npm install in the terminal to install every dependency, and the project is ready to go!
A small note: the package-lock.json file doesn't need to be copied.
Have fun experimenting with TypeScript! Good luck with the coding! ๐