I get "React not defined" when using express, create-react-app and babel-node

1k views Asked by At

I just wanted to enable server-side rendering with react and create-react-app.

I've written a server/index.js file which should return a simple react component as a string.

//require('import-export');
//require('babel-register')({ ignore: /\/(build|node_modules)\//, presets: ['react-app', 'es2015', 'react'] });
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const fs = require('fs');
const index = require('./index.js');
const react = require('react');
const reactServerDom = require('react-dom/server');
const renderToString = reactServerDom.renderToString;
const ourComponent = require('../src/App.js');
const app = express();

// Setup logger
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));

// Serve static assets - NEEDS TO BE ACTIVATED LATER WHEN RENDERTOSTRING WORKS!
//app.use(express.static(path.resolve(__dirname, '..', 'build')));

app.get('/', (req, res) => {
  const filePath = path.resolve(__dirname, '..', 'build', 'index.html');
  let result = '';
  fs.readFile(filePath, 'utf8', function (err, data) {
    if (err) {
      return console.log(err);
    }
    const ReactApp = renderToString(react.createElement(ourComponent));
    result = data.replace('{{SSR}}', ReactApp);
    res.send(result);
  });
});

const port = 9007;

app.listen(port, () => {
  console.log(`App listening on port ${ port }`);
});

module.exports = app;

The component that should be rendered is just the sample component which everyone gets from create-react-app:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

Inside my package.json I have following command to start the server with babel-node using the command yarn server or npm run server:

...
  "scripts": {
    "start": "react-scripts start",
    "server": "NODE_ENV=development babel-node --presets=es2015,react server/index.js",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
...

But I still get following error:

$ NODE_ENV=development babel-node --presets=es2015,react server/index.js
/home/sonnenfeld/ssr-render/src/logo.svg:4
React.createElement(
^

ReferenceError: React is not defined

And if I remove the svg from the component I get another error:

SyntaxError: /home/sonnenfeld/ssr-render/src/App.css: Unexpected token (1:0)
> 1 | .App {
    | ^
  2 |   text-align: center;
  3 | }
  4 |

I have already tried the babel hook with babel-register, but also no success.

What would be a good approach to transpile my server.js and all dependencies to vanilla javascript, when using create-react-app with express?

1

There are 1 answers

1
David Sonnenfeld On BEST ANSWER

Server Side Rendering can be really hard. So I switched entirely to next-js.

The problem with styled components was solved with an official workaround https://www.styled-components.com/docs/advanced#server-side-rendering