Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why I can't export export a declared function in ES6?

I have read docs from MDN, ok, mainly it's good about the new module feature, what makes me confused is the small things about export, now, let's see:

when I

export function foo(x) {
   return x * x;
}

or

export const foo = (x) => {
  return x * x
}

both works;

but if

const foo = (x) => {
  return x * x
}
export foo  // failed

I know here should be export {foo}, but, why? what's the difference, that should be work. glad to hear some genies ideas.

like image 214
gy134340 Avatar asked Dec 13 '22 18:12

gy134340


2 Answers

ES modules support only several syntax variations in order to be statically analyzed.

According to the reference, the variations are:

export { name1, name2, …, nameN };
export { variable1 as name1, variable2 as name2, …, nameN };
export let name1, name2, …, nameN; // also var, function
export let name1 = …, name2 = …, …, nameN; // also var, const

export default expression;
export default function (…) { … } // also class, function*
export default function name1(…) { … } // also class, function*
export { name1 as default, … };

export * from …;
export { name1, name2, …, nameN } from …;
export { import1 as name1, import2 as name2, …, nameN } from …;

export foo is not among them. It is not supported and cannot be used.

like image 178
Estus Flask Avatar answered Dec 18 '22 00:12

Estus Flask


I know here should be export {foo}, but why?

Because that's the syntax that was decided for. Notice that it's actually possible to export multiple variables from a single export declaration:

export { foo as foo, bar as bar }

It just doesn't flow well without braces.

like image 22
Bergi Avatar answered Dec 18 '22 00:12

Bergi