JS: Module. Import Export Example.
Example. Named Export
here's a sample library file lib.js:
// file name: lib.js const f1 = ((x) => (x + 1)); const f2 = ((x) => (x + 2)); export { f1, f2 };
here's a JavaScript file main.js that import the lib file:
// file name: main.js import { f1, f2 } from "./lib.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: lib2.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 lib2.js , and name it g import g from "./lib2.js"; console.log(g.f1(1));
And here's the HTML to load the main.js
<script type="module" src="./main.js"></script>