0

I want to turn this

function sum(a, b) {
  return a + b;
}
module.exports = sum;

into es6. I have babel preset 2015 but I still got error when I try to run below code:

export default sum(a, b) => {
    return a + b;
}

Anything wrong with my es6 function and export?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Alex Yong
  • 7,425
  • 8
  • 24
  • 41

1 Answers1

1

It would either be

const sum = (a, b) => {
   return a + b;
};

export default sum

or

export default (a, b) => {
  return a + b;
};

You can also try it out here: https://babeljs.io/repl, and see the transpiled code.

woutr_be
  • 9,532
  • 24
  • 79
  • 129
  • The first one would result in an error as `sum` would need to be defined first. `const sum = ...; export default sum;` however would work. – CodingIntrigue Feb 24 '17 at 08:23
  • @CodingIntrigue Seems to be okay - https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-2&targets=&browsers=&builtIns=false&code='use%20strict'%3B%0A%0Aexport%20default%20sum%20%3D%20(a%2C%20b)%20%3D%3E%20%7B%0A%20%20return%20a%20%2B%20b%3B%0A%7D%3B – woutr_be Feb 24 '17 at 10:52
  • Babel compiles fine, but you'd get a runtime `ReferenceError`. ES Modules run in Strict Mode and implicitly created global variables are not allowed. `let sum; export default sum = ...` would also get around that issue. – CodingIntrigue Feb 24 '17 at 11:02
  • Yeah, the first one is not what you want. It similar to doing `return sum = 42;` from a function. – Felix Kling Feb 24 '17 at 15:14