How can I reuse functions? I want to declare them once then include them in other files.
I created a module Global, containing some functions which I may want to add to other typescript files
I tried the following in another typescript file:
import test = require("./Global");
import * as testFunctions from "Global"
Both lines give errors saying the module cannot be found. The module is definitely visible to typescript as I am actually referencing this module at other places in the file, calling it's functions, which is working (EXAMPLE: Global.stopSpinner()).
Im not sure what I am doing wrong however, as I am following examples. Could someone explain me the correct way?
The import function imports text data by converting from external text representation to the internal format. The export function exports text data by converting from the internal format to the external text representation.
A function to be imported is already exported in its original file. You can import functions from a different file using the import keyword functionality. Import allows you to choose which part of a file or module to load. This will make this function available for use in our current file.
Yes, we can export the functions in TypeScript by using the 'export' keyword at the start of the function.
Export in TypeScript There is a simple design/compile time tool that you can use to stop your TypeScript code from accessing things it should not. With the export keyword, JavaScript adds a line to include the exported item to the module. There are two types of export statements: export default and normal export .
An example:
// global.ts
export function abc() {
}
// main.ts
import { abc } from "./global"
abc();
I suggest to read the introduction to ES6 modules from Mozilla.
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