0

Hoping this is just a small issue, but I have this in my Express server:

app.get('/', function(req, res) {
  res.send(ReactDOMServer.renderToString(React.createElement(App)));
});

But there's a problem when I hit:

this.posts = positions.map((bool, index) =>
  <Post key={index} pro={bool}/>
);

It doesn't seem to recognize the component part:

Unexpected token (19:6)
  18 |     this.posts = positions.map((bool, index) =>
> 19 |       <Post key={index} pro={bool}/>
     |       ^
  20 |     );
  21 |   }

Any help would be appreciated! Thank you!

2
  • Do you use babel-node and do you have .babelrc configured?
    – user6812877
    Jan 21, 2017 at 7:33
  • I don't, could you point me in the right direction? All I have right now are babel presets/plugins configured through webpack.
    – Peter Qiu
    Jan 21, 2017 at 7:46

2 Answers 2

0

In order to use JSX universally, you need to also configure Babel on your server. In order to run babel-node you need to install babel-cli like this:

npm install -g babel-cli

Inside your project, you need to configure .babelrc like this:

(These presets come as separate packages. For example, if you want to use react preset, you need to have babel-preset-react as project dependency.)

{
  "presets": ["es2015", "react"] // you can add or remove presets
}

Then in your code, where it shows you unexpected token:

this.posts = positions.map((bool, index) => (
  <Post key={index} pro={bool} />
));

Then you can refactor your express route like this:

// requires es2015 preset
// you can also use require
import { renderToString } from 'react-dom';

app.get('/', (req, res) => {
  res.send(renderToString(<App />));
});
0

You can either use the babel-cli directly as Adrian says or you can wrap your app with babel-register. This is only recommended in development environments though and you should compile/transpile your app using babel before running in production.

Assuming you already have your .babelrc set up with the react and es2015 plugins, set up an index.js with something like:

const fs = require('fs-promise');

fs.readFile('./.babelrc').then((babelrc) => {
  const config = JSON.parse(babelrc);
  require('babel-core/register')(config);
  require('./src/server');
});

where ./src/server is your node server app (Express, Hapi, etc.)

And to run it all NODE_ENV=development node index.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.