I'm trying to figure out how I can use some existing functions in my React app.
There is a javascript file called Foo.js and and associated typing Foo.d.ts
Foo.js has many functions and at the top I see
//I don't understand what the below lines re doing
var A = A || {};
A.B= A.B|| {};
A.B.C= A.B.C|| {};
A.B.C.Foo= A.B.C.Foo|| {};
(function ()
//here there are many functions
)();
Then in the d.ts file
declare namespace A.B.C.Foo
{
//here there are exported functions
}
Now I have my react components in another folder, and I wish to use the functions defined in the Foo.js file. How do I use them? I've tried adding the below to my component
///<reference path="../../../typings/@Test/Foo.d.ts" />
My component looks like below
const Component: React.FunctionComponent<IProps> = (props:Iprops) =>
{
//I'm trying to use the function here.
}
What do I need to do to import the functions? I have no idea how to proceed.
Edit: One more piece of information: In the html file I have a reference to Foo.js added in a script tag
" /> Edit: So I was able to get this to work. The accepted answer pointed me in the right direction with using global. Looks like Foo.js was already declared in a manner that the functions were available in React already. On the react side, adding the below reference path worked. To get type checking what I was missing was that that the .d.ts file exports a namespace so I had to prefix all functions with that namespace like so: A.B.C.Foo.FunctionName() ///The best way to expose functions to the other modules of your application is when a module provides a export statement:
// Foo.js
export const mySpecialFunction = () => {}
// otherFile.js
import { mySpecialFunction } from './Foo.js';
mySpecialFunction();
Otherwise, you will need to rely on window (considering your code runs on browser) to expose you function globally by import Foo.js somewhere (preferably on your app's entrypoint) and using the function:
// Foo.js
window.mySpecialFunction = () => {}
// index.js (entrypoint of your app)
import './Foo.js';
// otherFile.js
mySpecialFunction();
But about Typescript, you can't just define a namespace. It must match with a path alias you define on tsconfig.js which points to Foo.js.
The fact is that isn't clear what you are aiming.
Edit:
How would I do this "typescript as a global module attached to window"?
You could follow this documentation https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-d-ts.html. It will help you to define a global function or namespace.
Disclaimer: In a general way, do not rely on global modules as they decrease the code readibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With