11

I'm trying to run Babel through it's CLI using babel-node but I keep getting the Unexpected token export error. I understand that Babel 6 is all about plugins and that I need to set the plugin through .babelrc but it doesn't seem to work properly.

So here are my questions:

For those who are curious of what I'm trying to export, then here is the class:

'use strict';

class Factorial {
  static solve (num) {
    if(num === 0) return 1;
    else return num * Factorial.solve(num - 1);
  }
}

console.log(Factorial.solve(5))

export default Factorial;
iwatakeshi
  • 697
  • 3
  • 17
  • 31
  • 4
    FWIW, you shouldn't use a class if it has static methods only. Either use an object or in this case, simple have a single function. – Felix Kling Oct 31 '15 at 06:29
  • @FelixKling Thanks for the tip, I'm just used to using classes since I come from a C++/C#/Java background ;) – iwatakeshi Oct 31 '15 at 06:31

2 Answers2

16

The easiest way to get started is to use a preset.

First let's install our dependencies:

$ npm install --save-dev babel-cli babel-preset-es2015

Then add a build script to your package.json that runs Babel: (this is important because it will use your local version of babel-cli instead of a globally installed one)

"build": "babel input.js"

Your package.json should look like this:

{
  "name": "my-module",
  "devDependencies": {
    "babel-cli": "^6.x.x",
    "babel-preset-es2015": "^6.x.x"
  },
  "scripts": {
    "build": "babel input.js -o compiled.js"
  }
}

Finally you want to update your local .babelrc like this:

{
  "presets": ["es2015"]
}

Then you run npm run build and you're all set to go.

Also, does Babel 6's CLI have a global .babelrc option? It seems tedious if I have to install the plugins for every project that requires it...

That's a bad idea as it means you can't ever update it without updating every single one of your projects code. Having local versions means this potential error is less likely to occur.

Code Whisperer
  • 22,959
  • 20
  • 67
  • 85
James Kyle
  • 4,138
  • 4
  • 28
  • 41
  • Thanks! I realized that presets exists and did use it but it seems like the `import` keyword doesn't work? Would you know anything about this issue? – iwatakeshi Nov 01 '15 at 05:01
  • Might be a problem with your version of Babel. There were some early issues, try updating and if that doesn't work stop by the Slack channel for support. https://slack.babeljs.io/ – James Kyle Nov 02 '15 at 05:20
3

I received the same error, but my webpack/babel configs looked correct. By trial and error, I replaced export myFunction with export default myFunction and the error got resolved.


Later, I realized that the correct way of exporting is export {myFunction}. I implemented it and everything works fine.

Megidd
  • 7,089
  • 6
  • 65
  • 142