0

I'm trying to set up server side routing on a React project. Like always, I have used CRA. When I try to run the start command from my terminal, I get the error shown in the screen below: enter image description here

Can anyone help me get past this? I think the problem is that I'm using CRA because from what I've read, there seem to be some extra steps I need to take in order to get my app to read my babel config files when using CRA. I can't quite figure it out though. This is what my webpack.config.js file looks like:

var path = require('path')
var webpack = require('webpack')
var nodeExternals = require('webpack-node-externals')
var browserConfig = {
  entry: './src/browser/index.js',
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'bundle.js',
    publicPath: '/'
  },
  module: {
    rules: [
      { test: /\.(js)$/, use: 'babel-loader' },
    ]
  },
  mode: 'production',
  plugins: [
    new webpack.DefinePlugin({
      __isBrowser__: "true"
    })
  ]
}
var serverConfig = {
  entry: './src/server/index.js',
  target: 'node',
  externals: [nodeExternals()],
  output: {
    path: __dirname,
    filename: 'server.js',
    publicPath: '/'
  },
  mode: 'production',
  module: {
    rules: [
      { test: /\.(js)$/, use: 'babel-loader' }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      __isBrowser__: "false"
    }),
  ]
}
module.exports = [browserConfig, serverConfig]

This is my index.js file inside the server directory:

import React from "react";
import express from "express";
import cors from "cors";
import { renderToString } from "react-dom/server";
import App from "../App";
const port = 8000;
const server = express();
server.use(cors());
server.use(express.static("public"));
server.get("*", (req, res, next) => {
  const markup = renderToString(<App />);
  res.send(`
  <!DOCTYPE html>
  <html>
    <head>
        <title>SSR with RR</title>
    </head>
    <body>
        <div id="app">${markup}</div>
    </body>
  </html>
  `);
});
server.listen(port, () => {
  console.log(`Server launched on port ${port}`);
});

1 Answer 1

1

you are missing to declare @babel/preset-react preset. Include at your .babelrc file along the other configurations:

{
  "presets": [
    "@babel/preset-react",
    ...
  ]
}

make sure that you have as your devDependency:

npm i -D @babel/preset-react
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.