In previous development projects using VUE, the simple and crude way to do this was to mount methods on vue. Prototype, for example

Vue.prototype.myFn = () = > {
  console.log('myFn')}Copy the code

This can be called directly with this, this.myfn ().

React doesn’t seem to have this method, so after some searching, we found that we could mount the method to window, i.e

// global.ts
window.myFn = () = > {
  console.log('myFn')}Copy the code
// app.tsx entry file
import './global.ts'
Copy the code

But an awkward thing happens. Because TypeScript is used in the project, Property ‘myFn’ does not exist on type ‘Window & Typeof globalThis’. Property ‘myFn’ does not exist on type ‘Window & Typeof globalThis’.

You can use the TypeScript keyword DECLARE to change type restrictions and create a new shims.d.ts file in the root directory

// shims.d.ts
declare global {
  interfaceWindow { myFn? :Function}}Copy the code

Augmentations for the global scope can only be directly nested in external modules or ambient Module Declarations. [Global scope extensions can only be nested directly in an external module or environment module declaration]

Simply turn the shims.d.ts file into a module and make sure there are no member conflicts with other files

// shims.d.ts
export {}

declare global {
  interfaceWindow { myFn? :Function}}Copy the code

It can be called directly from window when other files are used, window.myfn ().

Done ✌️