ES6 default and named exports

时光总嘲笑我的痴心妄想 提交于 2021-02-18 22:39:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!