Introduction
ES Modules let you share and use code between files easily. They help organize your code like separate boxes you can open and use when needed.
Jump into concepts and practice - no test required
export const name = value;
export function myFunc() {}
import { name, myFunc } from './file.js';
// Default export
export default function() {}
import anyName from './file.js';export to share variables, functions, or classes from a file.import to bring those shared parts into another file.greeting that other files can import.export const greeting = 'Hello';sayHi.export function sayHi() {
console.log('Hi!');
}greeting constant and sayHi function from messages.js.import { greeting, sayHi } from './messages.js';
export default function() {
console.log('Default export');
}// file: mathUtils.js
export function add(a, b) {
return a + b;
}
export const pi = 3.14159;
// file: app.js
import { add, pi } from './mathUtils.js';
console.log('Add 2 + 3 =', add(2, 3));
console.log('Value of pi:', pi);.js are required in import paths in Node.js ES Modules.type: "module" in your package.json to enable ES Modules in Node.js.export to share code and import to use it elsewhere.export and import in Node.js ES Modules?exportexport keyword allows parts of a file (like functions or variables) to be shared with other files.importimport keyword is used to bring those shared parts into another file to use them.greet in an ES Module file?export function functionName() {} to export a function.node main.js?// utils.js
export const value = 5;
export function double(x) { return x * 2; }// main.js
import { value, double } from './utils.js';
console.log(double(value));utils.js exports a constant value = 5 and a function double that multiplies input by 2.main.jsvalue and double, then calls double(value) which is double(5), returning 10.// math.js
export function add(a, b) { return a + b; }
// app.js
import { add } from './math';
console.log(add(2, 3));import { add } from './math'; but misses the .js extension required in Node.js ES Modules.add is correctly exported with export function add(), so no error there.// data.js
const secret = 'hidden';
export const visible = 'shown';
export default function getSecret() { return secret; }// index.js
import getSecret, { visible } from './data.js';
console.log(visible);
console.log(getSecret());node index.js?getSecret is the default export function returning secret. visible is a named export with value 'shown'.import getSecret, { visible } correctly imports default and named exports. Logging visible prints 'shown'. Calling getSecret() returns 'hidden'.