Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing functions in typescript

Tags:

typescript

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?

like image 456
Kai Avatar asked Apr 18 '17 09:04

Kai


People also ask

What are import functions?

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.

Can you import a function in JavaScript?

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.

Can we export function in TypeScript?

Yes, we can export the functions in TypeScript by using the 'export' keyword at the start of the function.

What is import and export in TypeScript?

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 .


1 Answers

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.

like image 167
Paleo Avatar answered Oct 26 '22 17:10

Paleo