[英]ES6 export default function
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.js
file : 示例:在
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 ?
这不是很实用,任何解决方案或解决方法?
madox2's answer 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! 我希望这有帮助!
You can use named export instead 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";
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. 这应该是它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.