一、项目构建
-
1、创建文件夹并且初始化
npm init -y
-
2、安装
babel
依赖包yarn add @babel/cli @babel/core @babel/preset-env @babel/preset-typescript typescript -D
-
3、在项目下创建一个
babel.config.js
文件module.exports = { presets: [ [ '@babel/preset-env', { targets: { node: 'current', }, }, ], '@babel/preset-typescript', ], };
-
4、初始化
ts
的配置文件,关于配置文件的内容就不介绍,有兴趣的可以参考tsc --init
{ "compilerOptions": { "target": "es5", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": [ "src" ] }
-
5、在
package.json
中配置编译命令"scripts": { "babel": "babel src --out-dir dist --extensions \".ts\"" },
-
6、开心的写
typescript
代码
二、使用typescript
搭建express
项目
-
1、初始化项目
npm init -y tsc --init
-
2、修改
tsconfig.json
文件内容{ "compilerOptions": { "target": "es5", "module": "commonjs", "outDir": "./dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "baseUrl": "src" }, "exclude": ["node_modules"], "include": ["./src/**/*.ts"] }
-
3、安装
express
的依赖包yarn add express yarn add @types/express
-
4、在
src/index.ts
文件中书写代码import express, { Express, Request, Response, NextFunction } from 'express'; const PORT: number = 3000; const app: Express = express(); app.get('/', async (req: Request, res: Response, next: NextFunction) => { res.json({ code: 0, message: 'success', }); }); app.listen(PORT, () => { console.log(`服务已经启动:localhost:${PORT}`); });
-
5、在
package.json
中配置启动命令"scripts": { "build": "tsc", "start": "ts-node-dev --respawn src/index.ts", "dev": "nodemon --exec ts-node --files src/index.ts" },
开发环境启动命令可以是用
dev
或者start
,如果你要使用start
启动方式就要多安装两个依赖包yarn add ts-node-dev typescript -D