Express.js with TypeScript

Express.js with TypeScript

When working with TypeScript on server side in Node.js environment, we have 2 major options to consider: "tsc" and "ts-node"

TSC

  • Generates JS files from a given TypeScript source and outputs the JavaScript into specified "outDir" location
  • It compiles the code ahead of time, which commonly results in more optimized JS output
  • Performs static type checking which is useful for catching potential error early on
  • Great choice for production builds

Important: it does not make a copy of none TS files in output directory. Meaning that structure and style (e.g. ".html", ".css") have to get copied over to the output directory somehow. There are libraries like "copyfiles" to help with file duplication:

npm install copyfiles --save-dev
copyfiles -u 1 src/**/*.css dist/        

TS-NODE

  • Executes TypeScript code directly without explicit transpiling to JS
  • Transpiles the TS code using the TypeScript Compiler from a given source on a fly which commonly comes at the expense of optimization - as a result it runs slower than TSC produced code
  • Great choice for development and testing

Important: the "src" attribute of the "link" tag in the head of HTML document cannot be pointed to TypeScript file. This way scripting logic for DOM operations still has to be written in JS

Serving HTML using Express.js with TypeScript

To recap, Express JS is a very lightweight but powerful web development framework for Node.js. To learn more about I suggest to visit their official page: https://expressjs.com/

I would assume that you have Node and npm installed. If not, please visit their installation guide: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm

  • Navigate to desired folder and run "npm init" to initiate a new project. That will also create a basic "package.json" file.
  • Install dependencies

"devDependencies": {
    "@types/express": "^5.0.0",
    "@types/node": "^22.10.6",
    "copyfiles": "^2.4.1",
    "express": "^4.21.2",
    "nodemon": "^3.1.9",
    "rimraf": "^6.0.1",
    "typescript": "^5.7.3"
  },
  "dependencies": {
    "dotenv": "^16.4.7",
    "ts-node": "^10.9.2"
  }        

  • Run "npx tsc --init" to create a basic version of "tsconfig.json" file
  • Create a root folder (e.g. "public", "src" or whatever you want to call it). Create "index.ts" file in that folder
  • Under "src" folder create folder where you are going to store HTML templates

Open the "index.ts" file and define initial server setup:

import path from 'path';
import dotenv from 'dotenv';
import express, { Express, Request, Response } from 'express';

dotenv.config();
const rootPath = path.join(__dirname);

const app: Express = express();
const port = process.env.PORT || 3000;
app.use(express.static(rootPath));

app.get('/', (req: Request, res: Response) => {
    const filePath = path.join(rootPath, 'templates/initTemplate.html');
    res.sendFile(filePath);
});

app.listen(port, () => {
    console.log(`Running server on port: ${port}`);
});        

Run it with

nodemon --exec ts-node ./src/index.ts        

Navigate to "https://localhost:3000" to see your HTML template served.

Access localhost from another computer

  • To access localhost URL from another computer you need to know your computer's IP address
  • To retrieve it, open the command line and type "ipconfig /all"
  • Look for the IPv4 value under "Wireless LAN adapter Wi-Fi:" section
  • Access your server via "https://{IPv4-value}:3000"


要查看或添加评论,请登录

Ilya Kulikov的更多文章

社区洞察

其他会员也浏览了