Skip to main content

Modules

Modules are used to split up logic in an application. A module is just a file in JavaScript.

Modules can be imported and exported using the keywords import and export.

CommonJS

CommonJS is the default for Node.js. By using CommonJS, modules are exported using module.exports = function() {} and imported using the require syntax const {add} = require('./script');

module.exports.add = function(a, b) {
return a + b;
}

module.exports.subtract = function(a, b) {
return a - b;
}

----

const {add, subtract} = require('./util')

console.log(add(5, 5)) // 10
console.log(subtract(10, 5)) // 5

ES Modules (ECMAScript 2015 / ES6)

With ES6, import and export statements were added to allow more efficient tree-shaking builds and support fro==or both static and dynamic imports.

export const add = (x, y) => x + y;
export const subtract = (x, y) => x - y;

----

import { add } from './math.js';
console.log(add(2, 3)); // Output: 5

Default vs Named Import

CommonJS

module.exports.namedFunction = function () {};
module.exports = { namedFunction };

----

const defaultFunction = require('./');
defaultFunction.namedFunction();

or

const { namedFunction } = require('./');
namedFunction();

ES Modules

export const namedFunction = () => {}
export default function() => {}

----

import { namedFunction } from './';
namedFunction();

import defaultFunction from './';
defaultFunction();

import * as allNamedFunctions from './';
allNamedFunction.namedFunction();

Differences

Featurerequireimport
Module SystemCommonJSES6 (ECMAScript version 6)
Loading TypeSynchronous (modules are imported sequentially)Mostly static (modules are loaded in order at compile time, dynamic import is async)
PerformanceLess efficient due to synchronous loadingMore efficient with static imports due to predictability and async with dynamic imports
Memory UsageImports entire module, leading to potentially higher memory usageCan import selective components, reducing memory usage
Export AccessAccess to components exported by module.exportsAccess to components exported by export
ImplementationCan be used directly as it is the default method in Node.jsRequires ES6 or ECMAScript module support enabled
Usage in CodeCan be used anywhere in the programStatic imports are used at the top, dynamic can be used within the program