2 min read

Modules

As your JavaScript applications grow, it becomes important to organize your code into separate, reusable pieces. Modules allow you to do this by breaking up your code into multiple files. Each file is a module, and you can export variables, functions, and classes from a module to make them available to other modules. You can then import them into other modules where you need them.

ES6 Modules

ES6 introduced a standard module system for JavaScript.

export

You can export variables, functions, and classes from a module using the export keyword.

// lib.js
export const name = 'John';

export function sayHello() {
  console.log('Hello!');
}

export class Person {
  constructor(name) {
    this.name = name;
  }
}

// You can also have a default export
const myVar = 123;
export default myVar;

import

You can import variables, functions, and classes from another module using the import keyword.

// main.js
import { name, sayHello, Person } from './lib.js';
import myVar from './lib.js'; // Importing the default export

console.log(name); // "John"
sayHello(); // "Hello!"

const john = new Person('John');
console.log(john.name); // "John"

console.log(myVar); // 123

Using Modules in the Browser

To use modules in the browser, you need to tell the browser that a script is a module by adding type="module" to the <script> tag.

<script type="module" src="main.js"></script>

This enables the use of import and export in your scripts.

CommonJS Modules

Before ES6 modules became the standard, Node.js used a different module system called CommonJS. You might still see this in older Node.js projects.

In CommonJS, you use require() to import modules and module.exports to export them.

// lib.js
const name = 'John';

function sayHello() {
  console.log('Hello!');
}

module.exports = {
  name,
  sayHello
};

// main.js
const { name, sayHello } = require('./lib.js');

console.log(name); // "John"
sayHello(); // "Hello!"