koa+Typescript 构建Node 应用

1,602 阅读1分钟

koa

Typescript

创建项目及添加基础依赖

mkdir (project-name)
cd (project-name)
npm init
yarn add koa typescript ts-node nodemon
yarn add @types/koa

新建tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es2017",
        "noImplicitAny": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist",  // TS文件编译后会放入到此文件夹内
        "baseUrl": ".",
        "paths": {
            "*": [
                "node_modules/*",
                "src/types/*"
            ]
        }
    },
    "include": [
        "src/**/*"
    ]
}

安装typescript 相关依赖

yarn add reflect-metadata // 用来在声明的时候添加和读取元数据
yarn add routing-controllers koa-router  // 路由
yarn add koa-views jade // 视图
yarn add koa-bodyparser // 解析参数

创建koa服务

新建 src 目录 及在src 目录新增文件 app.ts

import 'reflect-metadata'; // this shim is required
import { createKoaServer, Action } from 'routing-controllers';
const views = require('koa-views');
const app = createKoaServer({
  routePrefix: '/',
  middlewares: [__dirname + '/middlewares/*.js'],
  controllers: [__dirname + '/controllers/**/*.js']
});
// 配置模板文件目录和后缀名
app.use(views(__dirname + '/views', {
  extension: 'jade'
}));
app.listen(3001, () => {
  console.log('Server is running at http://localhost:3000');
  console.log('init project \n');
  console.log('Press CTRL-C to stop \n');
});

修改 package.json 中script 模块

"scripts": {
    "start": "npm run serve",
    "serve": "node dist/app.js",
    "build": "npm run copy && npm run tslint && npm run build-ts",
    "build-ts": "tsc",
    "watch": "npm run tslint && npm run watch-ts && npm run watch",
    "watch-ts": "tsc -w",
    "copy": "cp -r views/ dist",
    "tslint": "tslint -c tslint.json -p tsconfig.json"
},

运行

// 开发模式
npm run watch
node dist/app.js 或者 利用 vs code debug 模式
// vs code debug
add configuration
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceFolder}\\dist\\app.js",
            "preLaunchTask": "tsc: build - tsconfig.json",
            "outFiles": [
                "${workspaceFolder}/dist/**/*.js"
            ]
        }
    ]
}