简体   繁体   中英

Isomorphic react, unexpected token <

I rebuilt my application to an isomorphic approach. Everything worked fine on my local enviroment (node version local and online is the same) But unfortunately after uploading the files to my webserver I get the following error message:

SyntaxError: .../index.js: Unexpected token (74:62)
  72 |                       friends: friends
  73 |                     }
> 74 |                     var reactString = ReactDOM.renderToString(<IndexApp {...props}/>)
                                                                     ^

This directly points to the < in <IndexApp..

My requirement list looks as following:

var React = require('react')
var ReactDOM = require('react-dom/server')

var IndexApp = require('../public/js/build/components/IndexApp').default
var PostApp = require('../public/js/build/components/PostApp').default

I can't find any proper solution to that. I gladly appreciate any hints. Thank you.

You need to transpile the jsx to javascript. You can do that with Babel , something like

babel my-file.js --presets react -o output.js

There are two options here : 1)For dev environment you can wrap jsx code like this

<script type="text/babel" src="yourfile"/>

and also include browser.min.js This will be transpiled in your browser.

2)For prod environment you need to transpile it first .You can do this on your local machine using babel

babel --presets es2015,react --minified financialFeed.js -o ./compiled/compiled.js

or you can do it online by going to

https://babeljs.io/repl/

In order for Javascript with JSX to work in the browser, it has to be transpiled first. You can do that within the page by including Babel and changing the script type to 'text/babel'. First, put this in the <head> of the page:

<script 
 src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>

And then wrap your jsx-containing Javascript like this:

<script type="text/babel">
 ... code goes here ...
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM