问题
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';
?
回答1:
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'; };
回答2:
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'; };
来源:https://stackoverflow.com/questions/36569961/es6-default-and-named-exports