Closed4
express, React SSR的なメモ
概要
express、React SSR , CSR的な 内容になります
環境
- express: 4.18.2
- React 18
- node 20
関連
作成したコード
- 関連パス
- /ssr
- /csr
- expressに、react ついかします
npm i --save react react-dom
npm i -D @types/react @types/react-dom
- package.json
{
"scripts": {
"start": "ts-node src/index.ts",
"dev": "ts-node-dev --respawn src/index.ts",
"build": "rimraf dist && tsc",
"deploy": "npm run build && vercel --prod"
},
"devDependencies": {
"@types/express": "^4.17.18",
"@types/node": "^20.8.0",
"@types/react": "^18.2.23",
"@types/react-dom": "^18.2.8",
"rimraf": "^3.0.2",
"ts-node": "^10.7.0",
"typescript": "^5.2.2"
},
"dependencies": {
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"csrf": "^3.1.0",
"dotenv": "^16.0.1",
"express": "^4.18.2",
"express-session": "^1.17.2",
"log4js": "^6.4.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"ts-node-dev": "^2.0.0"
}
}
- tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/src",
"target": "es5",
"sourceMap": false,
"strict": true,
"removeComments": true,
"esModuleInterop": true,
"moduleResolution": "node",
"jsx": "react-jsx"
},
"include": ["./src/**/*"],
"exclude": ["./src/test/*", "node_modules"]
}
SSR
- index.ts
index.ts
import { renderToString } from 'react-dom/server';
//
import {Ssr} from './views/ssr/App';
import {Csr} from './views/csr/App';
app.get('/ssr', (req: any, res: any) => {
try {
res.send(renderToString(Ssr()));
} catch (error) {
res.sendStatus(500);
}
});
- views/ssr/App.tsx
App.tsx
import * as React from 'react';
let i = 0;
export function Ssr() {
return (
<div>
<h1>SSR</h1>
<hr />
<p>welcome</p>
</div>
);
}
CSR
- js読み込む例です
- index.ts
index.ts
//Csr
app.get('/csr', (req: any, res: any) => {
try {
res.send(renderToString(Csr()));
} catch (error) {
res.sendStatus(500);
}
});
- views/csr/App.tsx
App.tsx
import * as React from 'react';
import {Layout} from './layout';
//
export function Csr() {
return (
<Layout>
<div>
<h1>CSR</h1>
<hr />
<div id="root"></div>
{/* JS */}
<script type="text/babel" src="/js/csr.js"></script>
</div>
</Layout>
);
}
- public/js/csr.js
csr.js
let items = [];
let message = "";
//
function App() {
const [updatetime, setUpdatetime] = React.useState("");
React.useEffect(() => {
(async () => {
console.log("#start");
message = "hoge";
updateTimestap();
})()
}, []);
//
const updateTimestap = function() {
const dt = new Date().toString();
setUpdatetime(dt);
}
//
return (
<div className="App">
<h1>Hello React by CSR</h1>
<hr />
<p>updatetime:{updatetime}</p>
<p>message: {message}</p>
<hr />
</div>
);
};
//
ReactDOM.createRoot(document.getElementById('root')).render(
<App />
);
このスクラップは2023/10/01にクローズされました