pk1m pk1m - 1 month ago 15
React JSX Question

React Serverside rendering Unexpected token, JSX and Babel

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.

Answer

You need to use babel/register (npm i babel --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-core babel-preset-es2015 babel-preset-react --save

require('babel-core/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/