node-ts

咸昀
2023-12-01
  • 搭建Node TS开发环境
    项目结构
npm init -y
npm i typescript ts-node-dev tslint @types/node -D
npm i sequelize-typescript@0.6.11
npm i sequelize@6.3.3
  1. 启动脚本
"scripts": {
	"start": "ts-node-dev ./src/index.ts -P tsconfig.json --no-cache",
	"build": "tsc -P tsconfig.json && node ./dist/index.js",
	"tslint": "tslint --fix -p tsconfig.json"
}
  1. 加入tsconfig.json
{
	"compilerOptions": {
		"outDir": "./dist",
		"target": "es2017",
		"module": "commonjs",//组织代码方式
		"sourceMap": true,
		"moduleResolution": "node", // 模块解决策略
		"experimentalDecorators": true, // 开启装饰器定义
		"allowSyntheticDefaultImports": true, // 允许es6方式import
		"lib": ["es2015"],
		"typeRoots": ["./node_modules/@types"],
	},
	"include": ["src/**/*"]
}
  1. 创建入口文件./src/index.ts
  2. 运行测试: npm start
  • TypeScript实现类装饰器和方法装饰
  • 基于装饰器的Router Validation Models
    anotation 注解
    @xxxxx 注解风格的装饰器
function decoate (target, property, descriptor) {
    const old = descriptor.value
    descriptor.value = msg => {
        msg = `==${msg}==`
        return old(msg)
    }
}

class Log {
    @decoate // 注解风格的装饰器
    print (msg) {
        console.log(msg)
    }
}
const log = new Log()
log.print('hello') // ==hello==
  • 基本服务器搭建
import * as Koa from 'koa'
import * as bodify from 'koa-body';
import * as serve from 'koa-static';
import * as timing from 'koa-xtime';

const app = new Koa();
app.use(timing());
app.use(serve(`${__dirname}/public`));
app.use(
    bodify({
        multipart: true,
        // 使用非严格模式,解析 delete 请求的请求体
        strict: false,
    }),
);
app.use((ctx: Koa.Context) => {
    ctx.body = 'hello'
})
app.listen(3000, () => {
    console.log('服务器启动成功');
});

运行命令 npm start
访问:http://localhost:3000/

 类似资料: