skip to Main Content

I have a CRA and want to have the first page generated statically to improve load time and SEO. The idea is to run a NodeJS script that renders the App document inside index.html.

Here is my code:

const { renderToString } = require("react-dom/server");
const App = require('./App');
const content = `<html><body>${renderToString(App)}</body></html>`
const fs = require('fs');
fs.writeFileSync('../public/index.html', content);

However, I have problems running it with NodeJS:

import React from 'react';
^^^^^^

SyntaxError: Cannot use import statement outside a module

Apparently, I have to build the source, but I don’t know how to do it. I’m using CRA to build my React files (actually, I’m using react-app-rewired, so I could customize the build process if I only knew how to do it).

What should I do to make it work?

2

Answers


  1. Chosen as BEST ANSWER

    I ended up using puppeteer and just saving the generated client-side code. Before that I spent hours stubbing out first window, then window.location, then window.localStorage, window.document, window.document.createElement, it never ended. With puppeteer, it was pretty easy.


  2. the error is from node: https://stackoverflow.com/a/59399717/13216797

    I know it’s not your question… but what about using Nextjs?

    Even without a node environment you can use the "next export" command to make a bundle that will work as it would static files while still being react…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search