How to export and import modules in Node.js
· Category: Node.js
Short answer
In CommonJS, use module.exports to export and require() to import. In ES modules, use export or export default and import.
Steps
CommonJS:
1. Create a file math.js with module.exports.add = (a, b) => a + b;.
2. In another file, import it with const math = require('./math.js');.
3. Use the function with math.add(2, 3);.
ES Modules:
1. Create a file math.mjs with export const add = (a, b) => a + b;.
2. In another file, import it with import { add } from './math.mjs';.
3. Use the function directly with add(2, 3);.
Tips
- You can destructure CommonJS imports:
const { add } = require('./math');. - ES modules require the full file path including the extension unless you use a bundler.
Common issues
Error: Cannot find moduleusually means the path is wrong or the file does not exist.- Mixing CommonJS
requirewith ES moduleimportin the same file causes a syntax error.