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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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/


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x