ES Modules in Node.js
Node.js supports standard JavaScript ES Modules using import and export. A project can use ES Modules by configuring the package appropriately, commonly through the type field in package.json or by using .mjs files.
ES Modules provide static import syntax and align Node.js code with the module system used by modern JavaScript applications.
ES Module Example
export function add(a, b) {
return a + b;
}
import { add } from './math.js';
console.log(add(2, 3));💡 The module exports a function and another module imports it using standard ES Module syntax.
Key Takeaways
- ES Modules use
importandexport. - Relative ES Module imports commonly require explicit file extensions.
- Use one module strategy consistently within an application.
Knowledge Check
Which syntax exports a named ES Module function?