Plug in Modules in JavaScript

In JavaScript there is different types of modules. You have Common JS modules, that NodeJS uses by default without even using Bable transpiler. Also there is ES2015 modules with a different plugin syntax. Both are used to bring in modules which can be other JavaScript files, but you also can bring in modules that are installed with NPM.

Common JavaScript modules

Create a simple js file named ‘mymodule.js’:

// make everything in this file available for the other files
module.exports = {
  name: 'Vlad',
  email: 'test@test.com'
}

In the app file bring this module file in:

const person = require('./mymodule'); // no .js extension!
console.log(person.name);

If you bring in a node module into you app use this:

const person = require('express');

ES2015 JavaScript modules

A slightly different syntax is used for ES2015+:

export const person = { //this variable can be accessed from other files
  name: 'Vlad',
  email: 'test@test.com'
}

In the app file bring in this module:

import { person } from './mymodule';
console.log(person.name);

If you need to import several variables/functions from one file:

import * as mod from './mymodule';

Exporting default object

The module file:

const greeting = 'Hello';
export default greeting;

In the app use no curly braces:

import greeting from './mymodule';
console.log(greeting);