Node.js Module System

Creating and importing modules

CommonJS Export

// module.js
module.exports = { # export object
    add: (a, b) => a + b,
    subtract: (a, b) => a - b
};
exports.multiply = (a, b) => a * b; # add to exports

CommonJS Import

const math = require('./module'); # import module
math.add(1, 2); # use exported function
const { add } = require('./module'); # destructure import

ES Modules Export

// module.mjs or with "type": "module" in package.json
export const add = (a, b) => a + b; # named export
export default (a, b) => a + b; # default export

ES Modules Import

import { add } from './module.mjs'; # named import
import add from './module.mjs'; # default import
import * as math from './module.mjs'; # import all

Built-in Modules

const fs = require('fs'); # no path needed
const path = require('path');