babel-plugin-autobind-function-decorators

1.0.1 • Public • Published

介绍

You can use plugin to automatically bind decorators to function properties in the class 你可以使用这个插件自动为 class 类中的函数属性绑定装饰器。支持一个 class 类中绑定部分函数和全函数绑定。

可在 babelwebpack 配置中使用

功能与使用

功能说明

  1. 支持给类中所有函数绑定装饰器
  2. 支持给类中部分函数绑定装饰器
  3. 支持自定义需要绑定的装饰器名称

具体使用

  1. babel.config.json 或者 webpack.config.jsonplugins 中增加配置。
/**
 * 用来自动绑定装饰器的插件
 * 1. 支持给类中所有函数绑定装饰器
 * 2. 支持给类中部分函数绑定装饰器
 * 3. 支持自定义需要绑定的装饰器名称
 * 
 * plugins 中的配置方式如下
 {
  "plugins": [
    ["babel-plugin-autobind-function-decorators", {
      "classes": [
        {
          "className": "Student", // 要增加装饰器的类
          "methods": ["getName", "method2"], // 类中要增加装饰器的函数
          "decoratorName": "Aop" // 自定义的装饰器
          "applyToAll":false, // 可选参数,类中函数不全部应用装饰器可以不写
        },
        {
          "className": "MyClass2",
          "applyToAll":true, // 装饰器是否要要应用到类中所有函数
          "decoratorName": "Decorator2"
        }
      ]
    }]
  ]
 }
 */
  1. 在 class 类中导入自定义的装饰器即可
import { Aop } from './aopDec';// 导入自定义的装饰器

class Student{
    private name;
    constructor(name:string){
        this.name = name;
    }
    
    getName(){
        return this.name
    }
}
const student = new Student('小明');
console.log(student.getName())

注意事项

  1. 如果ts项目,注意在 tsconfig.json 中启用对 decorators 的支持
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
  }
}
  1. 由于 decorator 的一些语法是一些尚未被正式纳入 ECMAScript 标准的实验性功能。需要增加一些插件配置
 ["@babel/plugin-proposal-decorators", { "legacy": true }],
 ["@babel/plugin-transform-class-properties", { "loose": true }],

注意增加我们的插件配置时,放到它们之前,因为 babel plugins 中内容从前往后执行,防止受影响

Package Sidebar

Install

npm i babel-plugin-autobind-function-decorators

Weekly Downloads

1

Version

1.0.1

License

ISC

Unpacked Size

5.22 kB

Total Files

3

Last publish

Collaborators

  • xiaogangzai