Basic
Basic start-up
This tutorial will guild to create a simple express.js web server from scratch with typescript.
1. Install packages
To init a new package.json, we have to init with the following command.
npm init -yAfter it, install the necessary packages express.
npm install expressFor typescript, we have to add the devDependencies for typescript to compile the type annotation.
npm install -D ts-node typescript @types/node @types/express2. Add tsconfig.json
Create a tsconfig.json and copy the folowing stuff to your root folder.
{
"compilerOptions": {
"strict": true,
"module": "commonjs",
"target": "es6",
"outDir": "dist",
"lib": ["es6", "dom"],
"sourceMap": true,
"allowJs": true,
"esModuleInterop": true,
"moduleResolution": "node",
"noImplicitReturns": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"noUnusedLocals": true
},
"exclude": ["node_modules", "test", "dist"]
}3. Add server.ts
Create a folder named server.ts at the root, then copy the following stuff in the file.
import express, { Request, Response } from "express";
const app = express();
// http://localhost:8080/
app.get("/", function (req: Request, res: Response) {
res.end("Hello mom!");
});
const PORT = 8080;
app.listen(PORT, () => {
console.log(`Listening at http://localhost:${PORT}/`);
});4. Start up
After created the server.ts, type the following command in the terminal.
ts-node server.ts5. Set up package.json
Actually, you can script the following command in your package.json for start up next time.
{
"name": "my-website",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "ts-node server.ts" // Add this line in your "scripts"
}.
// ... Remaining stuffAfter saving, you may type npm start for start up the server.
npm start6. Folder Structure
At the final, your project should have the following structure.
.
βββ π node_modules
βββ server.ts
βββ package.json
βββ tsconfig.json