0
0
Node.jsframework~5 mins

ES Modules import and export in Node.js

Choose your learning style9 modes available
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.
When you want to split your code into smaller, reusable parts.
When you need to use functions or data from another file.
When building a Node.js app that uses modern JavaScript features.
When you want to keep your code clean and easy to maintain.
When sharing code between different projects or files.
Syntax
Node.js
export const name = value;
export function myFunc() {}

import { name, myFunc } from './file.js';

// Default export
export default function() {}
import anyName from './file.js';
Use export to share variables, functions, or classes from a file.
Use import to bring those shared parts into another file.
Examples
Exports a constant named greeting that other files can import.
Node.js
export const greeting = 'Hello';
Exports a function named sayHi.
Node.js
export function sayHi() {
  console.log('Hi!');
}
Imports the greeting constant and sayHi function from messages.js.
Node.js
import { greeting, sayHi } from './messages.js';
Exports a default function without a name. It can be imported with any name.
Node.js
export default function() {
  console.log('Default export');
}
Sample Program
This example shows how to export a function and a constant from one file and import them in another. The app.js file uses the imported parts to print results.
Node.js
// 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);
OutputSuccess
Important Notes
File extensions like .js are required in import paths in Node.js ES Modules.
Use type: "module" in your package.json to enable ES Modules in Node.js.
Default exports let you import without curly braces, named exports require curly braces.
Summary
ES Modules help organize code by exporting and importing parts between files.
Use export to share code and import to use it elsewhere.
Remember to enable ES Modules in Node.js and include file extensions in imports.