ES6 export default function

2020-05-25 07:30发布

问题:

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 :

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

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 ?

回答1:

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

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!



回答2:

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";


回答3:

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.