初始化项目
进入项目文件夹,执行 npm init
命令,一路回车,最后输入 yes
即可创建项目,生成项目的 package.json
文件,文件内容如下
1 | { |
安装相关依赖
- 用
npm install express
安装express
- 用
npm install typescript @types/node @types/express -D
安装相关ts
相关依赖 - 用
npm install @babel/cli @babel/core babel-plugin-module-resolver hjson -D
安装相关babel
相关依赖 - 用
npm install ts-node nodemon tsconfig-paths -D
安装开发环境相关依赖 - 用
npm install hjson rimraf -D
安装其它依赖
配置项目
- 在根目录下创建
tsconfig.json
,配置ts
1 | { |
- 在根目录下创建
babel.config.js
文件配置babel
,本项目中只用到了babel
编译路径别名的功能
1 | const hjson = require("hjson"); |
- 在根目录下创建
nodemon.json
,配置开发环境
1 | { |
编写测试代码
- 创建
scr/index.ts
文件
1 | import * as express from "express"; |
- 创建
scr/utils/log.ts
文件
1 | import { isDev } from "./env"; |
- 创建
scr/utils/env.ts
文件
1 | export const isDev = process.env.NODE_ENV !== "production"; |
配置相关脚本
nodemon
开发环境编译命令:"dev:server": "nodemon"
ts-node
开发环境编译命令:"dev:ts:server": "ts-node -r tsconfig-paths/register src/index.ts --files"
- 生产环境编译命令:
"build:server": "rimraf ./dist && tsc --build ./tsconfig.json && babel ./dist/index.js --out-dir ./dist"
- 生产环境启动服务命令:
node ./dist/index.js
最终 package.json
1 | { |
开发环境
在根目录执行 npm run dev:server
或者执行 npm run dev:ts:server
就可以启动服务,访问 http://localhost:8000
,即可在浏览器中看到 hello world
,注意 npm run dev:ts:server
文件有更改后不会自动重启服务
生产环境
在根目录执行 npm run build:server
,然后再执行 npm run start:server
就可以启动服务,访问 http://localhost:8000
,即可在浏览器中看到 hello world
目录结构
1 | src // 源码目录 |