Home > AI > Frontend > ReactJS >

Server-Side-Rendering (2)

The sample code for Server-Side-Rendering (TypeScript version) has been successfully tested. The entire process is quite simple, as depicted below:

  1. Utilize the command: npx create-react-app my-app --template typescript to create a project.
  2. Simplify App.tsx to
import React from 'react';

const App: React.FC = () => {
  return (
    <div>
      <h1>Hello, Server-Side Rendering!</h1>
    </div>
  );
};

export default App;

3. Modify the package.json file by installing dependencies such as ts-node and include the line "homepage": "./".

Package typescript shouldn’t be worried, as it was integrated during the project initiation with version ^4.9.5. Changing the version is not advisable, as it may lead to compatibility issues.

4. Create a folder named server and add a file named server.js within it.

import express, {Application, NextFunction, Request, Response} from "express";
import fs from "fs";
import path from "path";

import React from "react";
import ReactDOMServer from "react-dom/server";

import App from "../src/App";



const PORT = 8000;
const app: Application = express();
app.use("^/$", (req: Request, res: Response, next: NextFunction) => {
  fs.readFile(path.resolve("../build/index.html"), "utf-8", (err, data) => {
    if (err) {
      console.log(err);
      return res.status(500).send("Some error happened")
    }

    return res.send(
      data.replace(
        '<div id="root"></div>',
        `<div id="root">${ReactDOMServer.renderToString(React.createElement(App))}</div>`
      )
    )
  })
})


app.use(express.static(path.resolve(__dirname, "..", "build")))

app.listen(PORT, ()=>{
  console.log(`App launched on ${PORT}`);
})

5. Generate a tsconfig.json file within the server folder.

{
  "compilerOptions": {
    "target": "es2016",
    "jsx": "react",
    "module": "commonjs",
    "rootDir": "../",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

6. Compile the client-side code using npm run build at the same directory level as the package.json file.

7. Compile the server-side code using tsx --project tsconfig.json within the server folder.

Problem: exports not supported by ES module

Previously, I included "type": "module" in package.json. When I used tsc --package tsconfig.json to compile server code, it repeatedly raised complaints about exports not being supported by ES module, as TypeScript handles conversion between CommonJS and ES. However, removing “type”: “module” resolved the issue.

Problem: file “../build/index.html” not found.

Initially, I set outDir = "../dist", but encountered an issue where the compiled file couldn’t locate ../build/index.html. I resolved this by removing the setting and allowing all compiled JavaScript files to remain in their original directory, which resolved the path issue.

Note: I utilized ES for both server and client, enabling the use of import instead of require (CommonJS) on both sides.

Conclusion

The description above may have some imperfections, the complete code can be checked here https://github.com/tutehub/sample-reactjs/tree/develop/test-ssr-ts

Leave a Reply