背景
对于没有系统搭建过node项目的同学给予指导
项目搭建
请确保全局安装了TS
npm install -g typescript
- npm 初始化, 填入相应信息用于生成package.json
npm init
- 安装typescript 相关依赖
yarn add typescript --dev
yarn add tslib @types/node --dev
yarn add ts-node-dev --dev
- 在根目录下新建src文件夹, 在src下新建index.ts 入口文件
- 配置tsconfig.json
ts 配置项 可以参考网上教程
{
"compilerOptions": {
"target": "es2020",
"module": "CommonJS",
"outDir": "./dist/",
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "Node",
"strict": true,
"skipLibCheck": true,
"baseUrl": "./src",
"paths": {
"@/*": [
"./*"
]
},
"typeRoots": [
"./typings/"
],
"plugins": [
{
"transform": "typescript-transform-paths"
},
{
"transform": "typescript-transform-paths",
"afterDeclarations": true
}
]
},
"include": [
"src/**/*"
, "config/xprofiler.config.js" ],
"exclude": [
"node_modules"
]
}
- 安装KOA相关依赖
yarn add koa
yarn add koa-body
yarn add koa-router
yarn add @types/koa-router --dev
- 创建路由文件, src/router/index.ts
import { Context, Next } from "koa";
import koaBody from "koa-body";
import Router from "koa-router";
const router = new Router()
router.get('/api/xxx', koaBody(),async (ctx:Context, next: Next) => {
const body = 'hello world';
ctx.body = body;
next();
})
export default router;
- 更新src/index.ts, 添加路由
import Koa from "koa";
import router from "./router";
const app = new Koa();
app.use(router.routes());
app.listen(3000, () => {
console.log("server start 3000");
});
- 更新package.json的启动命令
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "ts-node-dev --files src/index.ts"
}
-
yarn start 启动
访问localhost:3000/api/xxx
这里只是实现一个简单的ts + koa的node server, 帮助没有做过node项目的同学上手, 消除恐惧, 具体依赖包的使用,可以看对应的官网教程