ES6 by default and named export

I am trying to understand import and export by default. I have a seemingly basic requirement that I don’t understand how to configure.

I want to be able to import both:

//app.js import Mod from './my-module' import { funcA, funcB } from './my-module' console.log('A', Mod.funcA(), funcA()); // A aa console.log('B', Mod.funcB(), funcB()); // A aa 

When I try, the closest way to do this, I get the following:

 //my-module.js export function funcA() { return 'a'; }; export function funcB() { return 'b'; }; export default {funcA, funcB} 

My problem is that I do not want to reindex each function into the default export. I just want to define my functions and then make sure that they are exported, so I can use them anyway.

Suggestions? Or I need to use import * as Mod from './my-module'; ?

+6
source share
2 answers

You can omit the default export and use import as the syntax:

 //app.js import * as Mod from './my-module' import { funcA, funcB } from './my-module' console.log('A', Mod.funcA(), funcA()); // A aa console.log('B', Mod.funcB(), funcB()); // B bb 
 //my-module.js export function funcA() { return 'a'; }; export function funcB() { return 'b'; }; 
+7
source

Import the contents of the entire module once with * as name :

 import * as Mod from './my-module'; 

Then assign them to separate constants using destructuring:

 const { funcA, funcB } = Mod; 

For export, just use named export:

 export function funcA() { return 'a'; }; export function funcB() { return 'b'; }; 
+5
source

All Articles