CNode

nodejs 环境下如何实现装饰器

问答
Dddzyan发布于7 年前最后回复7 年前6 回复7667 浏览0 收藏

在nodejs 环境下如何实现装饰器,有了解的大佬指点下哈,想实现如下功能。

class Boy {
  @run
  speak() {
    console.log("I can speak");
  }
}
function run() {
  console.log("I can run");
}

let tj = new Boy();
tj.speak();
查看回复

回复 (6)

Y
yuu2lee4#1·7 年前

babel、typescript

D
ddzyan#2·7 年前
引用 yuu2lee4babel、typescript

@yuu2lee4 我弄好了配置文件 .babelrc

"plugins": [
  ["@babel/plugin-proposal-decorators", { "legacy": true }],
  ["@babel/plugin-proposal-class-properties", { "loose" : true }]
]

但是要如何使用呢?

W
weiketa#3·7 年前

webpack 先编译下,再node执行

D
ddzyan#4·7 年前
引用 weiketawebpack 先编译下,再node执行

@weiketa 感谢,我试试

Z
zuohuadong#5·7 年前
引用 ddzyan@weiketa 感谢,我试试

@ddzyan

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    return true;
  }
}
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    console.log('Before...');

    const now = Date.now();
    return next
      .handle()
      .pipe(
        tap(() => console.log(`After... ${Date.now() - now}ms`)),
      );
  }
}

参见: https://docs.nestjs.cn/6/firststeps

D
ddzyan#6·7 年前
引用 zuohuadong@ddzyan 参见: https://docs.nestjs.cn/6/firststeps

@zuohuadong nestjs 框架我已经在使用了(非常好),现在还考虑的是如何给 koa2 实现装饰器的功能

参与回复
登录后即可参与回复。登录