Express.js with TypeScript
Ilya Kulikov
Senior Test Automation Engineer at Caesars Sportsbook & Casino | TDD, BDD, Mobile Automation | Playwright, Cypress, Selenium, Appium | Java, Python, JavaScript, Node.js | Kubernetes, Docker, AWS
When working with TypeScript on server side in Node.js environment, we have 2 major options to consider: "tsc" and "ts-node"
TSC
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
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
领英推荐
"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"
}
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