ES6 ~ Modules - rohit120582sharma/Documentation GitHub Wiki

With ES2015 (ES6), we get built-in support for modules in JavaScript. Like with CommonJS, each file is its own module.

Each module is a piece of code that is executed once it is loaded and executed in strict mode by default.

To make objects, functions, classes or variables available to the outside world it’s as simple as exporting them and then importing them where needed in other files. A module can export multiple things and have only one default export.

Module import and export are hoisted. They have a static structure: what is imported and exported cannot be changed at runtime. The import and export statements have no dynamic parts (no variables etc. are allowed) and never nested inside a condition.


Exporting

You can export members one by one. What’s not exported won’t be available directly outside the module:

export const myNumbers = [1, 2, 3, 4];
const animals = ['Panda', 'Bear', 'Eagle']; // Not available directly outside the module

export function myLogger(){
	console.log(myNumbers, animals);
}

export class Alligator{
	constructor(){
		// ...
	}
}

Or you can export desired members in a single statement at the end of the module:

export { myNumbers, myLogger, Alligator };

Exporting with alias

You can also give an aliases to exported members with the as keyword:

export { myNumbers, myLogger as Logger, Alligator };

Default export

You can define a default export with the default keyword:

export default function myLogger(){
	console.log(myNumbers, pets);
}

Importing

Importing is also very straightforward, with the import keyword, members to be imported in curly brackets and then the location of the module relative to the current file:

import { myLogger, Alligator } from 'app.js';

Importing with alias

You can also alias members at import time:

import myLogger as Logger from 'app.js';

Importing all exported members

You can import everything that’s imported by a module like this:

import * as Utils from 'app.js';

This allows you access to members with the dot notation:

Utils.myLogger();

Importing a module with a default member

You import the default member by giving it a name of your choice. In the following example Logger is the name given to the imported default member:

import Logger from 'app.js';

And here’s how you would import non-default members on top of the default one:

import Logger, { Alligator, myNumbers } from 'app.js';

Example

//------ lib.js ------
export let counter = 3;
export function incCounter() {
	counter++;
}
//------ main1.js ------
import { counter, incCounter } from './lib';

// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4

// The imported value can’t be changed
counter++; // TypeError

⚠️ **GitHub.com Fallback** ⚠️