Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 default and named exports

I am trying to understand named and default exports. I have a seemingly basic requirement which I don't understand how to setup.

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 a a
console.log('B', Mod.funcB(), funcB()); // A a a

When I try, the closest way of doing this I get to is the following:

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

export default {funcA, funcB}

My trouble is that I don't want to reindex each functions in the default export. I just want to define my functions and then make sure they are exported so I can use them either way.

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

like image 947
mraxus Avatar asked Apr 12 '16 10:04

mraxus


2 Answers

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

//app.js
import * as Mod from './my-module'
import { funcA, funcB } from './my-module'

console.log('A', Mod.funcA(), funcA()); // A a a
console.log('B', Mod.funcB(), funcB()); // B b b
//my-module.js
export function funcA() { return 'a'; };
export function funcB() { return 'b'; };
like image 178
CodingIntrigue Avatar answered Oct 03 '22 16:10

CodingIntrigue


Import entire module's contents once using * as name:

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

Then assign them to separate constants using destructuring:

const { funcA, funcB } = Mod;

For export just use the named exports:

export function funcA() { return 'a'; };
export function funcB() { return 'b'; };
like image 32
Ori Drori Avatar answered Oct 03 '22 15:10

Ori Drori