MENU
ReactDOMServer
Server-side Rendering (SSR) allows dynamic components to be served to the clients as static HTML. This can improve loading speed and enhance search engine optimization (SEO).
To set up a Node.js Express server that supports SSR with React:
mkdir MyProjectcd MyProjectnpm initnpm install express react react-dom npm install --save-dev webpack webpack-cli webpack-node-externals @babel/core ¿ babel-loader @babel/preset-env @babel/preset-react concurrently nodemon |
'express' is a very popular Node.js web framework.
'webpack' bundles your .js files into a single file.
'babel' compiles your 'import' statements (preset-env) and JSX statements (preset-react) into native JavaScript code.
'concurrently' allows you to run the webpack watcher and the 'nodemon' server in parallel.
'nodemon' allows you to launch a Node.js server that updates itself automatically as it watches for changes in the source files.
To set up the assets bundler webpack for our use, add a file named 'MyProject/webpack.config.js' with the following contents:
RESETRUNFULL
const js = {
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/preset-react"],
},
}, };const serverConfig = {
mode: "development",
target: "node",
node: {
__dirname: false,
},
entry: {
"server.js": "./server.js"
},
module: {
rules: [js],
},
output: {
path: "D:/xampp/htdocs/my-react/test/test4/dist/",
filename: "[name]",
}, }; const clientConfig = {
mode: "development",
target: "web",
entry: {
"home.js": "./public/home.js"
},
module: {
rules: [js],
},
output: {
path:
"D:/xampp/htdocs/my-react/test/test4/dist/public",
filename: "[name]",
}, }; module.exports = [serverConfig, clientConfig];
'entry' specifies the files to start with when trying to follow 'import' statements. 'output' specifies the directory to place the bundled-up files.
Lastly, edit the file 'package.json':
... "scripts": { "start":"webpack && concurrently \"webpack --watch\" \"nodemon .\\dist\\server.js\"" },...... |
Running 'npm start' will compile all the server-side .js JSX files onto the directory dist/, and launch the Node.js server. (We will describe server.js in the following section.)