9

I'm having trouble finding the correct way to use babel to allow me to use jsx in serverside.

Node-jsx was deprecated for babel. It seems like babel-core/register is whats supposed to be used but I still get unexpected token issues.

I created a repo with the problem im having.

https://github.com/pk1m/Stackoverflow-helpme

When I run node app or npm run watch-js I keep getting unexpected token referring to the JSX code '<'.

How do I get babel to transpile JSX, or am I completely off, thanks.

Dmitry Shvedov
  • 3,169
  • 4
  • 39
  • 51
pk1m
  • 286
  • 1
  • 4
  • 12

1 Answers1

23

You need to use babel-register (npm i babel-register --save). And run on your server:

require('babel-register')({
    stage: 0
});

You can omit stage 0 if you aren't using experimental babel features. Also you might prefer to put those options in .babelrc instead.

Note that it will only work for files required AFTER calling that (so it would not have an effect on the file you include it in).

You could also have the presets and other options in a .babelrc file.

For babel 6x:

npm i babel-register babel-preset-es2015 babel-preset-react --save

require('babel-register')({
    presets: ['es2015', 'react']
});

Note: there are also stage 0-2 presets.

For watching as you've written in your package.json you could try a CLI command like the one facebook are suggesting in the note here (or use webpack):

babel --presets react es2015 --watch app/ --out-dir build/
Zach Bloomquist
  • 5,309
  • 29
  • 44
Dominic
  • 62,658
  • 20
  • 139
  • 163
  • ok, I'll try that when I get home. Is JSX an experimental babel feature? – pk1m Nov 02 '15 at 16:23
  • 1
    @pk1m no jsx and other es6 features will work, stage 0 is for proposed things like `static` in es7, and other experimental stuff (static is nice if you're using React.Component instead of React.createClass) – Dominic Nov 02 '15 at 16:44
  • ok, I used `require('babel/register')` but it says it was deprecated for `require('babel-core/register')`. So I used that instead if you can see in my git. Still throws errors for '<' – pk1m Nov 02 '15 at 18:17
  • @pk1m are you using babel 5 or 6? 6 is different – Dominic Nov 02 '15 at 18:53
  • I'll use whichever one that I can get to work. In my example app its babel-core v6 – pk1m Nov 02 '15 at 19:46
  • @pk1m personally I'm having trouble getting 6 to work for everything, it was released a few days ago and not everything is working smoothly yet. For me though it's es7 features I am having trouble with so I'll update the post – Dominic Nov 02 '15 at 20:02
  • 1
    this looks super promising because I've tinkered around with different packages and i could only get es6 OR jsx to work. Never both. Ill update when i get home to try it. thank you! – pk1m Nov 02 '15 at 20:31
  • 1
    Note that `babel/register, babel-core/register` are now deprecated in favor of `babel-register`. – Zach Bloomquist Aug 14 '18 at 18:57