Module System
The module system in JavaScript provides a way to organize and structure code by splitting it into separate files called modules. Each module can export values, such as variables, functions, or classes, that can be used in other modules. Modules can also import these exported values from other modules.
Exporting Values
To export a value from a module, you can use the export keyword followed by the value or values you want to export. For example, to export a single value:
1export const message = 'Hello, world!';Or to export multiple values:
1export const name = 'John Doe';
2export const age = 30;Importing Values
To import values from a module, you can use the import keyword followed by the value or values you want to import, enclosed in curly braces. For example, to import a single value:
1import { message } from './module';Or to import multiple values:
1import { name, age } from './module';Renaming Imports and Exports
If you want to use a different name for an imported or exported value, you can use the as keyword to rename it. For example, to export a value with a different name:
1export { message as greeting };And to import a value with a different name:
1import { greeting as welcome } from './module';Default Exports
In addition to named exports, a module can also have a default export. This is the primary value or functionality that the module exports by default. To define a default export, you can use the default keyword. For example:
1// module.js
2
3export default function sayHello(name) {
4 console.log(`Hello, ${name}!`);
5}
6
7// app.js
8
9import sayHello from './module';
10
11sayHello('John');xxxxxxxxxx// ES6 module syntax// Exporting a single valueexport const message = 'Hello, world!';// Exporting multiple valuesexport const name = 'John Doe';export const age = 30;// Importing a single valueimport { message } from './module';// Importing multiple valuesimport { name, age } from './module';// Renaming imports and exportsexport { message as greeting };import { greeting as welcome } from './module';// Default exports// module.jsdefault export function sayHello(name) { console.log(`Hello, ${name}!`);}// app.jsimport sayHello from './module';sayHello('John');


