在之前使用 vue 开发项目时,简单粗暴的办法就是将方法挂载到 vue.prototype 上,比如
在使用时可直接使用 this 来调用, 即 this.myfn()。
但是 react 貌似没有这种写法,于是经过一番查找发现可以将方法挂载到 window 上,即
但是尴尬的事情发生了,由于项目中使用的是 typescript,因此会报错 property 'myfn' does not exist on type 'window & typeof globalthis'. ['属性'myfn'在类型'window & typeof globalthis上不存在]
可以使用 typescript 关键字 declare 来更改类型限制,在根目录下新建 shims.d.ts 文件
此时还会报错 augmentations for the global scope can only be directly nested in external modules or ambient module declarations. [全局作用域的扩展只能直接嵌套在外部模块或环境模块声明中]
只需将 shims.d.ts 文件变成模块即可,也可确保与其他文件没有成员冲突
在其他文件使用时可直接用 window 来调用,即 window.myfn()。