简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM