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
I ended up using puppeteer and just saving the generated client-side code. Before that I spent hours stubbing out first
window
, thenwindow.location
, thenwindow.localStorage
,window.document
,window.document.createElement
, it never ended. With puppeteer, it was pretty easy.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…