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. Themodule
object contains theexports
object (module.exports
). Themodule
object also contains meta-information, such asid
,parent
, andchildren
.exports
- a plain JavaScript object, which may be augmented to expose functionality to other modules. Theexports
object is returned as the result of a call torequire()
.require()
- a function is used to import modules, returning the correspondingexports
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';