0
votes

I would like to do the initial render for my React application on the server side, but am having trouble importing and using React components without using something like babel/register (which is not suitable for production).

I would rather not have to compile my server side code for production, but would like to load an node-suitable React component to send to the client via res.send(React.createElement(Html)).

When I run this I get...

Unexpected token <

I assume this is because my components render method returns <!doctype html>...</html.

Is there a way I can have Node render a React component without having to use babel/compiling code before deploying?

2

2 Answers

0
votes

Is there a way I can have Node render a React component without having to use babel/compiling code before deploying?

No. Since JSX isn't real JavaScript, you need to transpile it at some point, either ahead of time (in a build script) or at run time (using babel-register).

Personally I ignore babel's advice to not use babel-register in production. It works just fine, I always cache + prime responses so performance isn't relevant. I'm open to hearing why transpiling with babel-register is bad though.

0
votes

Short answer, yes.

this is from the official docs:

ReactDOMServer

The react-dom/server package allows you to render your components on the server.

ReactDOMServer.renderToString

string renderToString(ReactElement element)

Render a ReactElement to its initial HTML. This should only be used on the server. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.

If you call ReactDOM.render() on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.

ReactDOMServer.renderToStaticMarkup

string renderToStaticMarkup(ReactElement element)

Similar to renderToString, except this doesn't create extra DOM attributes such as data-react-id, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes.

However, if you want to use JSX you have to use babel, otherwise, you can use Reacts JS Syntax.

Here is a link to an example:

https://github.com/mhart/react-server-example