Nodejs And Es6 Differences

Node uses CommonJS which is require and exports

Good resource : http://2ality.com/2014/09/es6-modules-final.html

CommonJs main use = server

const english = require('./english');
const spanish = require('./spanish');
 
module.exports = {
    english: english,
    spanish: spanish
}

ES6 Modules (AMD) main use = browser

ES6 modules uses import and export

I find this one quite convenient: simply write your code as if there were no outside world, then label everything that you want to export with a keyword.

ES6 import/export example

//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}
 
//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

If you want to, you can also import the whole module and refer to its named exports via property notation:

//------ main.js ------
import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5

Nodejs same example

//------ lib.js ------
var sqrt = Math.sqrt;
function square(x) {
    return x * x;
}
function diag(x, y) {
    return sqrt(square(x) + square(y));
}
module.exports = {
    sqrt: sqrt,
    square: square,
    diag: diag,
};
 
//------ main.js ------
var square = require('lib').square;
var diag = require('lib').diag;
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

Default

Modules that only export single values are very popular in the Node.js community. But they are also common in frontend development where you often have constructors/classes for models, with one model per module. An ECMAScript 6 module can pick a default export, the most important exported value. Default exports are especially easy to import.

The following ECMAScript 6 module “is” a single function:

//------ myFunc.js ------
export default function () { ... };
 
//------ main1.js ------
import myFunc from 'myFunc';
myFunc();

Class Export as well

//------ MyClass.js ------
export default class { ... };
 
//------ main2.js ------
import MyClass from 'MyClass';
let inst = new MyClass();
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License