装饰器可以干什么,有何优势
使用装饰器前首先要生成一个配置文件 tsc --init
打开
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
类装饰器
const Base:ClassDecorator = (target) => {
target.prototype.xiaoman = 'xm'
target.prototype.__fn = () => {
console.log('1111')
}
console.log(target)
}
@Base
class Http {
}
const http = new Http() as any
http.__fn()
/Base(Http)
比如Http类里面东西有很多,不想看里面代码只想增加一些东西,上面写一个类装饰器
通过target构造函数,给原型上加属性或者方法,target是http类的构造函数
不破坏结构前提下添加属性和方法,起修饰作用
函数柯里化
const Base = (name:string) => {
const fn:ClassDecorator = (target) => {
target.prototype.xiaoman = 'xm'
target.prototype.__fn = () => {
console.log('1111')
}
}
return fn
}
@Base('xiaoyu')
class Http {
}
const http = new Http() as any
http.__fn()
roullup打包ts
现在文件夹生成包管理文件 npm init
生成配置文件roullup.config.js 默认导出 export default{}
生成src文件夹 文件夹下存放index.ts
生成public文件夹 文件夹下存放index.html
生成ts配置文件 tsc --init