JavaScript, Node.js, and Express make for a potent combination when developing server-side applications. However, as your application grows and when collaborating with developers worldwide, maintaining code quality becomes a challenge. This is where TypeScript can be your ally.
In this extensive guide, we will walk you through setting up TypeScript in an Express application, highlighting key concepts for beginners.
Prerequisites
Before diving into TypeScript setup, ensure you have the following prerequisites:
Now, let’s embark on our TypeScript journey:
mkdir node-express-typescript
cd node-express-typescript/
npm init --yes
This will create a package.json
file with default settings based on your npm configuration.
package.json
is set up, let’s add Express to your project:
npm install express dotenv
Now, create a basic Express server in an index.js
file:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 8000;
app.get(‘/’, (req, res) => {
app.listen(PORT, () => {To start the server, run:
node index.js
npm i -D typescript @types/express @types/node
These packages ensure TypeScript understands the type definitions for Express and Node.js.
tsconfig.json
TypeScript projects rely on a tsconfig.json
file for configuration. Generate it using:
npx tsc --init
This file provides various configuration options, including the target JavaScript version, module system, strict type-checking, and more. Be sure to specify an outDir
for your compiled code.
Here’s a snippet of the tsconfig.json
file:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "dist"
}
}
.ts
ExtensionRename your index.js
file to index.ts
to indicate it’s a TypeScript file. Modify the code to:
import express from 'express';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
app.get(‘/’, (req, res) => {
res.send(‘Hello, TypeScript World!’);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
nodemon
and concurrently
. Install them as dev dependencies:
npm i -D nodemon concurrently
Add the following scripts to your package.json
:
"scripts": {
"start": "node dist/index.js",
"dev": "concurrently \"npm run watch-ts\" \"npm run start\"",
"watch-ts": "tsc -w",
"build": "tsc"
}
Run your development server using:
npm run dev
nodemon
will automatically restart your server upon file changes.
© 2013 - 2024 Foreignerds. All Rights Reserved