用Typescript开发NodeJS项目

本文示例用Typescript写一个基于ExpressJS的REST API项目

第一步:

全局安装Typescript

npm install -g typescript

在项目路径下,执行:

tsc --init

产生一个tsconfig.json文件,并在文件中添加下配置:

"moduleResolution": "node"

第二步:

npm --init

npm初始化,并安装以下package

npm install --save express

npm install --save body-parser

npm install --save-dev @types/node

npm install --save-dev @types/express

npm install --save-dev @types/body-parser

@types的package是typescript版本。

第三步:

编写REST API的typescript代码:

app.ts

 1 import express from 'express';
 2 import bodyParser from 'body-parser';
 3 
 4 import todoRoutes from './routes/todos';
 5 
 6 const app = express();
 7 
 8 app.use(bodyParser.json());
 9 
10 app.use(todoRoutes);
11 
12 app.listen({port: 3000});

routes/todo.ts

 1 import Router from "express";
 2 
 3 import { Todo } from "../models/todo";
 4 
 5 let todos: Todo[] = [];
 6 
 7 const router = Router();
 8 
 9 router.get("/", (req, res, next) => {
10   res.status(200).json({ todos: todos });
11 });
12 
13 router.post("/todo", (req, res, next) => {
14   const newTodo: Todo = {
15     id: new Date().toISOString(),
16     text: req.body.text,
17   };
18 
19   todos.push(newTodo);
20 
21   res.status(201).json({ message: "Added Todo", todo: newTodo, todos: todos });
22 });
23 
24 router.put("/todo/:todoId", (req, res, next) => {
25   const tid = req.params.todoId;
26   const todoIndex = todos.findIndex((todoItem) => todoItem.id === tid);
27   if (todoIndex >= 0) {
28     todos[todoIndex] = { id: todos[todoIndex].id, text: req.body.text };
29     return res.status(200).json({ message: "Updated todo", todos: todos });
30   }
31   res.status(404).json({ message: "Could not find todo for this id." });
32 });
33 
34 router.delete("/todo/:todoId", (req, res, next) => {
35   todos = todos.filter((todoItem) => todoItem.id !== req.params.todoId);
36   res.status(200).json({ message: "Deleted todo", todo: todos });
37 });
38 
39 export default router;

models/todo.ts

1 export interface Todo{
2     id: string;
3     text: string;
4 }

第四步:

执行 tsc 可以编译所有ts,但是nodejs不能执行ts代码,用 node app.js 启动node

在tsconfig.json中添加编译选项:

"outDir": "./dist"

可以将所有的js编译到一个目标路径下

"rootDir": "./src"

可以指定项目源文件路径,建议把所有ts文件放到这个路径下