ES6默认和命名导出 [英] 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.
建议?还是我必须使用 import *作为来自'./my-module';
的Mod ??
Suggestions? Or do I have to use import * as Mod from './my-module';
?
推荐答案
您可以省略默认导出,并使用import作为语法:
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'; };
这篇关于ES6默认和命名导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!