JS - Best Practices (Importing/Exporting in ES6)

Importing with ES6 :

ES6 provides us with various flavors of importing :

We can import an entire file :

import 'underscore';


Named imports :

import { sumTwo, sumThree } from 'math/addition';

 

Rename the named imports :

import {
sumTwo as addTwoNumbers,
sumThree as sumThreeNumbers 
} from 'math/addition';

 

Import all the things (also called namespace import) :

import * as util from 'math/addition';

 

Import a list of values from a module :

import * as additionUtil from 'math/addition';
const { sumTwo, sumThree } = additionUtil;

 

Exporting with ES6 :

With ES6, we have various flavors of exporting :

Named Exports :

export let name = 'David';
export let age = 25;​​

 

Exporting a list :

function sumTwo(a, b) {
    return a + b;
}

function sumThree(a, b, c) {
   return a + b + c;
}

export { sumTwo, sumThree }; 

 

Export functions, objects and values (etc.) simply by using the export keyword :

export function sumTwo(a, b) {
     return a + b;
}

export function sumThree(a, b, c) {
    return a + b + c;
}

 

Export default bindings :

function sumTwo(a, b) {
    return a + b;
}

function sumThree(a, b, c) {
   return a + b + c;
}

let api = {
  sumTwo,
  sumThree
};


export default api;

/* Which is the same as

export { api as default };

*/

 

Always use the export default method at the end of the module. It makes it clear what is being exported, and saves time by having to figure out what name a value was exported as.

 
 

js best practices