3

I am trying to export the result of a function in ES6. The function is unimportant - the following examples work for: const func = input => input

This works:

const a = 'foo'
const b = 'bar'

export default {
  a: func(a),
  b: func(b)
}

whereas these hit the error: SyntaxError: Unexpected token, expected ,:

export {
  a: func(a),
  b: func(b)
}

also:

export {
  func(a) as a,
  func(b) as b
}

Could you explain why? This does not seem to cover the above cases.

Community
  • 1
  • 1
Henry Heath
  • 1,072
  • 11
  • 19
  • can you include the original code, there's nothing wrong with the example you have given - are you using a transpiler? – mikeapr4 Apr 18 '17 at 16:03

2 Answers2

5

You can do

const aArg = 'foo'
const bArg = 'bar'

export const a = func(aArg);
export const b = func(bArg);

Named exports need a variable name to export, they can't export arbitrary expression results.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • Thanks. I know what I can do, but I don't understand what I can't do. Why isn't `func(a) as a` equivalent to giving the result of `func(a)` a name? – Henry Heath Apr 18 '17 at 16:11
  • `X as Y` is specifically `variable name AS variable name` so you can't call a function there. I guess it could technically be allowed, but it doesn't seem like it would come up very often since usually you're exporting a variable that exists already. – loganfsmyth Apr 18 '17 at 16:17
  • do you have a reference for that? – Henry Heath Apr 18 '17 at 16:33
  • 1
    @Henry: Grammar rules for `export`: https://www.ecma-international.org/ecma-262/7.0/#sec-exports . – Felix Kling Apr 18 '17 at 16:49
2
export default ...

You're exporting a single Object, Class, Function, etc.

export (Object, Class, Function) ...

You're exporting many Objects, Classes, Functions, etc. so you'll have to assign it to a name.

The first example is a little like if you teach at a school and have one student. You know who that student is and how to call him because he's the only one there. The second example, however, is like teaching a class with many students, you'll want some type of naming to call on the correct student(s).