0

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?

ulu
  • 5,872
  • 4
  • 42
  • 51

2 Answers2

0

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...

Noriller
  • 342
  • 1
  • 4
  • 12
  • I know about NextJS but I have a pretty big project in production already and I can't just rewrite it with NextJS. Next time I'll be wiser. – ulu Jun 30 '21 at 09:30
0

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.

ulu
  • 5,872
  • 4
  • 42
  • 51