This question might be dum. I am a beginner for typescript. In file A, I want to call a function defined in file B. How do I do this?
TypeScript also shares the same concept of a module. Any file which contains a top-level import or export is considered a module. The module is designed to arrange a code written in TypeScript and used as a local scope. Modules are basically scripts written in separate files.
The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum. When exporting a module using export = , TypeScript-specific import module = require("module") must be used to import the module.
Importing TypeScript files dynamically into JavaScript requires additional compilation step, which is troublesome to write for many. Popular typescript-require package seems to be obsolete and doesn't allow much customization.
You need to export the function in the file:
// File B
export function exampleFunction() {}
You can then import it in the other file for use:
// File A
import { exampleFunction } from 'path/to/fileb';
Use the appropriate import
and export
statements.
Given the following file layout:
├── a.ts
└── b.ts
a.ts
import {myFn} from 'b';
myFn();
b.ts
export function myFn() {
/* ... */
}
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