Plain SSR React app compiler
It runs Webpack under the hood to bundle application. Client part and server part allowing React to be server side rendered.
Preconditions
SSR React app written in Typescript
Commands
- development mode:
compiler dev
- prod bundle:
compiler build
- bundle analyzer:
compiler build -a
Entry points
- src/index.server.tsx
- src/index.client.tsx
Example of usage
Folder structure
.
├── dist
│ ├── bundles.json
│ ├── index.js
│ └── static
│ ├── gz
│ │ ├── main.js.gz
│ │ └── react.js.gz
│ ├── js
│ │ ├── main.js
│ │ └── react.js
│ └── media
│ └── 6576f3a9a340ac02328d.jpg
├── node_modules
├── public
│ └── favicon.ico
├── src
│ ├── assets
│ │ └── media
│ │ └── logo.jpg
│ ├── index.client.tsx
│ ├── index.server.tsx
│ └── root.tsx
├── package.json
└── tsconfig.json
src/root.tsx
import type { FC } from 'react';
import React from 'react';
const Root: FC = () => {
return (
<>
<img alt="logo" src={require('./assets/media/logo.jpg')} />
<div>Root of React application.</div>
</>
);
};
export default Root;
src/index.server.tsx
import fs from 'node:fs';
import path from 'node:path';
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import Root from './root';
const app = express();
const bundles = JSON.parse(fs.readFileSync(path.join(__dirname, './bundles.json'), 'utf-8'));
app.use('/', express.static(path.join(__dirname, '../public')));
app.use('/static/media', express.static(path.join(__dirname, './static/media')));
app.use('/static/css', express.static(path.join(__dirname, './static/css')));
app.use('/static/fonts', express.static(path.join(__dirname, './static/fonts')));
app.use(
'/static/gz',
express.static(path.join(__dirname, './static/gz'), {
setHeaders: res => {
res.setHeader('Content-Type', 'text/javascript');
res.setHeader('Content-Encoding', 'gzip');
}
})
);
app.use('*', (req, res) => {
const app = <Root />;
const markup = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="${bundles.main}" defer></script>
<script src="${bundles.react}" defer></script>
<title>Document</title>
</head>
<body>
<div id="root-container">
${renderToString(app)}
</div>
</body>
</html>
`;
res.setHeader('Content-Type', 'text/html');
res.end(markup);
});
app.listen(3000, () => console.log('Server is listening on http://localhost:3000'));
src/index.client.tsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import Root from './root';
if (module?.hot) module.hot.accept();
const container = document.getElementById('root-container');
const root = createRoot(container!);
root.render(<Root />);
Known problems
https://github.com/pmmmwh/react-refresh-webpack-plugin/issues/725