ES6 default and named exports
Asked Answered
P

2

7

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';?

Plutonic answered 12/4, 2016 at 10:3 Comment(0)
Y
9

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'; };
Yalonda answered 12/4, 2016 at 10:10 Comment(2)
So the import Mod from ’./my-module‘ is not to be used in the way asked above?Plutonic
It can be used as above, but I see no reason for the duplication of funcA/funcB in the default exportYalonda
G
5

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'; };
Giraldo answered 12/4, 2016 at 10:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.