@inkefe/create-decorator

支持在高阶函数基础上直接创造一个es6装饰器, 并可以兼容箭头函数、静态函数、普通prototype函数, 可以说是万能装饰器

Usage no npm install needed!

<script type="module">
  import inkefeCreateDecorator from 'https://cdn.skypack.dev/@inkefe/create-decorator';
</script>

README

create-decorator

项目简介

  1. 这个库有什么用?

虽然高阶函数可以对函数进行包装, 但是对于类而言, 直接使用es6的decorator对类进行装饰写法会更简洁也更可读, 如:

// hoc
class A {
  constructor () {
    this.sendMsg = needLogin(this.sendMsg)
  }
  sendMsg = () => {}
}

// es6 decorator
class A {
  @needLogin
  sendMsg = () => {}
}

那么如何将一个高阶函数快速转换为一个es6可以认识的装饰器呢? 可以参考decorate

  1. 那么createDecoratorcore-decoratorsdecorate有什么区别?
  • 支持箭头函数写法的装饰(decorate没实现), 并且内置了绑定this, 用起来更简洁
  • 双兼容, 即: 通过createDecorator创建的装饰器即可以对类进行装饰, 还可以保留继续对普通的函数进行包装的功能

综上: createDecorator是一个万能的装饰器创造器

安装

# devDependencies
npm install @inkefe/create-decorator -D

# dependencies
npm install @inkefe/create-decorator -S

使用文档

第一步: 创建装饰器

import createDecorator from '@inkefe/create-decorator'
import lodash from 'lodash'

// 直接传入高阶函数进行创建
const xxxDecorator = createDecorator(fn => (...args) => xxx, ...args)

// 与第三方高阶函数结合
const xxxDecorator = createDecorator(lodash.throttle, 300)

第二步使用装饰器

  1. 普通函数结合
import { compose } from 'redux'

const fn = () => { console.log('具体的业务函数') }

// 已创建的装饰器, 继续可以当做之前的高阶函数使用, 对fn进行装饰
const fnProxy = xxxDecorator(fn)

// 也支持compose
const fnProxyComposed = compose(xxxDecorator2, xxxDecorator1)(fn)
  1. 与类结合

兼容以下四种情况

class A {
  // 兼容静态函数
  @xxxDecorator
  static fn () {}

  // 静态函数箭头函数
  @xxxDecorator
  static fn = () => {}

  // prototype下函数
  @createDecorator(lodash.throttle, 300)
  @xxxDecorator
  fn () {}

  // prototype下箭头函数
  @xxxDecorator
  fnArrow = () => {}
}

项目介绍

  1. 可以在src目录下进行开发, 通过npm run example

  2. 开发完成一定要维护README, 开发完成一定要维护README, 开发完成一定要维护README

其中使用文档 部分应该全部替换为, 具体module的使用文档, 而不是保留ik-modules-pro的使用说明, 谨记!!!

  1. 构建
npm run build

会构建到lib目录下: create-decorator.development.jscreate-decorator.production.min.js

  1. 发布
# 补丁迭代
npm run publish:patch

# 小版本迭代
npm run publish:minor

# 大版本迭代
npm run publish:major

会将代码发布到npm中inkefe组下, 如果没有权限请联系李宝旭orleader开通npm组权限

  1. CHANGELOG.md中维护修改内容