Javascript ES6 导出默认功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35541864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:51:23  来源:igfitidea点击:

ES6 export default function

javascriptecmascript-6babeljs

提问by sisimh

can I export more than one function per file ? it seems like when I do that , the second function ovverides the first one ,

我可以为每个文件导出多个函数吗?似乎当我这样做时,第二个函数会覆盖第一个函数,

example : in my index.jsfile :

示例:在my index.js文件中:

export default function aFnt(){
    console.log("function a");
}
export default function bFnt(){
    console.log("function b");
}

then when I import it in my file :

然后当我将它导入我的文件时:

import aFnt from "./index";

console.log("aFnt : ",aFnt);

the result of the console.log is bFnt

console.log 的结果是 bFnt

what exactly is the case here ? do I have to create a new file per function ? that is not very practical , any solution or workaround ?

这里究竟是什么情况?我必须为每个函数创建一个新文件吗?这不是很实用,有什么解决方案或解决方法吗?

回答by Bobby Matson

madox2'sanswer totally works if you want to import named functions.

如果您想导入命名函数,madox2 的答案完全适用。

If you still want to import the default, there's another technique:

如果您仍然想导入默认值,还有另一种技术:

function a() {}

function b() {}

export default { a, b }

and when you import:

当您导入时:

import myObject from './index.js';

myObject.a(); // function a
myObject.b(); // function b

I hope this helps!

我希望这有帮助!

回答by madox2

You can use named exportinstead of default:

您可以使用命名导出而不是默认值:

export function aFnt(){
    console.log("function a");
}
export function bFnt(){
    console.log("function b");
}

and import it like:

并像这样导入:

import {aFnt, bFnt} from "./index";

回答by hannad rehman

there are couple of ways to export and import objects/functions

有几种方法可以导出和导入对象/函数

export function first() {}
export function second() {}

in other file

在其他文件中

import { first, second} from './somepath/somefile/';

if you want to use default, in general if there is only one export in a file it should be a default export. but if you for some reasons want two functions as default then you have to club them as a object and export that object as default

如果要使用默认值,通常如果文件中只有一个导出,则应为默认导出。但是如果你出于某些原因想要两个函数作为默认值,那么你必须将它们作为一个对象并将该对象导出为默认值

function first() {}
function second() {}
const funcs= {"first":first,"second":second}
export default funcs;

in other file

在其他文件中

import funcs from './somepath/somefile/';
funcs.first();funs.second();

this should be it.

这应该是它。