Dorokhov.codes

04. Modules

There are two methods to work with modules: CommonJS and ES6.

CommonJS method

This method we can use only for Node.js, not a browser. CommonJS describes a simple syntax for JavaScript programs to import other JavaScript programs into their context. This specification describes the use of the following variables:

  • module – an object representing the module itself. The module object contains the exports object (module.exports). The module object also contains meta-information, such as id, parent, and children.
  • exports - a plain JavaScript object, which may be augmented to expose functionality to other modules. The exports object is returned as the result of a call to require().
  • require() - a function is used to import modules, returning the corresponding exports object.

Export syntax:

function myModule() {
    this.hello = function() {
        console.log('Hello');
    }
}

module.exports = myModule;

Import syntax:

const myModule = require('./module'); // module.js file.

More simple example:

// math.js
module.exports.add = function(c, d) {
    return c + d;
};
const math = require('math');
math.add(2, 3);

ES6 modules

Export syntax:

export let one = 1;
let two = 2;
export {two};
export function sayHi() {
    console.log('Hello');
}

Import syntax:

import {one, two} from './main'; // main.js file.
import {one as first} from './main'; // main.js file.
import * as data from './main'; // main.js file.
console.log(data.one);

As we can see the exporting entity is always an object. But we can export a single entity:

export default function sayHi() {
    console.log('Hello');
}
import hiFunc from './main';