在之前使用 vue 开发项目时,简单粗暴的办法就是将方法挂载到 Vue.prototype
上,比如
Vue.prototype.myFn = () => {
console.log('myFn')
}
在使用时可直接使用 this
来调用, 即 this.myFn()
。
但是 React 貌似没有这种写法,于是经过一番查找发现可以将方法挂载到 window 上,即
// global.ts
window.myFn = () => {
console.log('myFn')
}
// App.tsx 入口文件
import './global.ts'
但是尴尬的事情发生了,由于项目中使用的是 TypeScript,因此会报错 Property 'myFn' does not exist on type 'Window & typeof globalThis'.
['属性'myFn'在类型'Window & typeof globalThis上不存在]
可以使用 TypeScript 关键字 declare
来更改类型限制,在根目录下新建 shims.d.ts
文件
// shims.d.ts
declare global {
interface Window {
myFn?: Function
}
}
此时还会报错 Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.
[全局作用域的扩展只能直接嵌套在外部模块或环境模块声明中]
只需将 shims.d.ts
文件变成模块即可,也可确保与其他文件没有成员冲突
// shims.d.ts
export {}
declare global {
interface Window {
myFn?: Function
}
}
在其他文件使用时可直接用 window
来调用,即 window.myFn()
。
大功告成✌️
如果有写的不对不好的地方,还请各位大佬指正批评啦~