简体   繁体   中英

Isomorphic React and JSX - rendering component as string on server

I'm trying to render an extremely simple component on the server before passing to the client, transforming using gulp and babelify like so:

gulp.task("react-assessment", function(){
  return browserify("./app/assessment/react/components/app.react.js")
    .transform(babelify)
    .bundle()
    .pipe(source("reactBundle.js"))
    .pipe(gulp.dest("./browser"))
});

The component works fine on the client:

var React = require("react");
var ReactDOM = require("react-dom");

var Title = React.createClass({
  render: function(){
    return <h1>Hello World</h1> 
  }
});

module.exports = ReactDOM.render(
  <Title/>, 
  document.getElementById("react-assessment")
);

However when I require the file in Node.js with Express, the server crashes with unexpected token

return <h1>Hello World</h1> 
           ^
SyntaxError: Unexpected token <

When I've used the old methodology of using /** @jsx React.DOM */ at the top of the component file, there were no problems.

Route:

var express = require('express'),
    router = express.Router(),
    ReactDOMServer = require("react-dom/server");  
    JSX = require('node-jsx').install({
      extension: '.jsx'
    }),
    AssessmentComponent = require("../react/components/app.react.jsx"); 

Where am I going wrong?

Solved by using babel/register. No need for React.DOM

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