JavaScript Modules
A module is a JavaScript file that shares some of its code with other files. Modules keep big programs organised, and avoid clashes of names.
Named exports
// math.js
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
// app.js
import { PI, add } from "./math.js";
console.log(PI);
console.log(add(2, 3));
Output of the above program is
3.14159
5
Default export
A file can have one default export. You can give it any name when you import it.
// greet.js
export default function greet(name) {
return "Hello, " + name;
}
// app.js
import greet from "./greet.js";
console.log(greet("Robin"));
Output of the above program is
Hello, Robin
Rename and import everything
import { add as sum } from "./math.js";
import * as MathTools from "./math.js";
console.log(sum(1, 2));
console.log(MathTools.PI);
Output of the above program is
3
3.14159
Use modules in HTML
Add type="module" to the script tag. Modules are loaded in strict mode and are deferred automatically.
<script type="module" src="app.js"></script>
Note:
Modules do not work if you open the HTML file by double click (file://). Run a small local server, for example with the VS Code “Live Server” extension. Node.js also supports modules, when the file ends with .mjs or package.json has "type": "module".
Summary
exportshares code,importuses it.- Named exports use braces, a default export does not.
- Load with
<script type="module">. - Next: Regular Expressions.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |