How to Import and Export Functions in JavaScript

 

export


An export declaration is used to export values ​​from a JavaScript module. The exported values ​​can then be imported into other programs using an import declaration or dynamic import. The value of an imported binding can change in the module that exports it - when a module updates the value of a binding it exports, the update will be visible in its imported value.

In order to use an export declaration in a source file, the file must be interpreted by the runtime as a module. In HTML, this is done by adding type="module" to the <script> tag or by importing another module. Modules are automatically interpreted in strict mode.

Each module can have two different export types, a named export and a default export. You can have multiple named exports per module, but only one default export. 

//test.js

export { fun2 , var2 };

// export individual features (can export var, let,
// const, function, class)

export let var1 = Math.sqrt(2);
export function fun() { /* ... */ };

 

//another file

import { carName as var2 , fun2  } from 'test.js';

Tags:

Share:

Related posts