最近终于上手了node服务,这样一来前端的技术栈又拓宽了许多。这次的项目是公司内部项目用的是nestjs,头一次接触到nestjs最深刻的印象就是打来给你用到了es7的装饰器。在项目开始的时候就预料到要写博客了,知识点很多那就先从装饰器开始吧。
装饰器在其他的语言上已经被广泛的使用了如java,py等。js es7的装饰器可以分为四种分别是类装饰器、方法装饰器、变量装饰器、参数装饰器。装饰器本身也相当于是封装了一个逻辑方法,在使用的时候通过@标识符直接调用。
目前浏览器和node对装饰器的支持还不是很好需要安装相应的babel。
我自己的测试项目的话是用vite,因此还涉及到了ts,我的配置是如下:
tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true
}
}
vite.config.ts
import typescript from "@rollup/plugin-typescript";
export default defineConfig({
plugins: [
typescript({
include: ["src/page/nestjs/**/*"],
exclude: ["node_modules/**/*"],
}),
react({
babel: {
plugins: [
["@babel/plugin-proposal-decorators", { legacy: true }],
["@babel/plugin-proposal-class-properties", { loose: true }],
],
},
}),
],
});
example
const decoratorTest = () => {
function classDecorator(classObj: any) {
console.log("classDecorator", classObj);
}
function functionDecorator(target: User, name: string, descriptor: any) {
console.log("functionDecorator", target, name, descriptor);
}
function filedDecorator(filed: string) {
return function (target: User, name: string, descriptor: any) {
console.log("filedDecorator", target, name, descriptor, filed);
};
}
function valueDecorator(target: User, propertyKey: string) {
console.log("valueDecorator", target, propertyKey);
}
function paramsDecorator(
target: any,
methodName: string,
paramsIndex: number
) {
console.log("paramsDecorator", target, methodName, paramsIndex);
}
@classDecorator
class User {
@valueDecorator
public name: string = "234234";
constructor() {}
@filedDecorator("234234234")
@functionDecorator
getName() {
return "111";
}
testParams(@paramsDecorator params: string) {
console.log(params);
}
}
let user = new User();
console.log(user.getName());
user.testParams("234234");
};
前端的话装饰器的使用暂时还不是很多,目前的前端有使用到的场景也就是mobx。
对于装饰器的话个人更把装饰器看成是一种另类的封装。不过这里也得到了一定的启发就是函数柯里化的应用。例如上面例子中的functionDecorator装饰器,普通装饰器是不能直接传递参数的,通过包裹一层函数的方式然后返回一个函数的方式就可以实现装饰器的传参。