JS: Module. Import Export Example.
Example. named export
here's a sample library file math.js:
// file name: math.js const f1 = ((x) => (x + 1)); const f2 = ((x) => (x + 2)); export { f1, f2 };
here's a JavaScript file main.js that import the math file:
// file name: main.js import { f1, f2 } from "./math.js"; console.log("Calling f1 from module. Result is" , f1(1));
And here's the HTML to load the main.js
<script type="module" src="./main.js"></script>
Example. default export
// file name: chem.js // export a object export default { f1: ((x) => x + 1), f2: ((x) => x + 2), }; // note, no name is given to the object
// file name: main.js // import a value from chem.js , and name it g import g from "./chem.js"; console.log(g.f1(1));
And here's the HTML to load the main.js
<script type="module" src="./main.js"></script>