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>
note, the type="module" is required.
Example. Default Export
// file name: chemistry.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 chemistry.js , and name it g import g from "./chemistry.js"; console.log(g.f1(1));
And here's the HTML to load the main.js
<script type="module" src="./main.js"></script>