我正在学习 React 服务器端渲染。使用 Koa 搭建服务端。按照官方文档,我安装react
了react-dom
:
yarn add react react-dom
接下来在我的服务器端条目中:
import Koa from 'koa'
import Router from '@koa/router'
import { renderToString } from 'react-dom/server'
import ReactDOMServer from 'react-dom/server';
import Home from '../client/components/HomePage'
const app = new Koa()
const router = new Router()
const content = ReactDOMServer.renderToString(Home)
// print logger
app.use(async (ctx, next) => {
await next()
const rt = ctx.response.get('tt')
console.log(`${ ctx.method }-${ ctx.url }-${ rt }`)
})
// set time
app.use(async (ctx, next) => {
const start = Date.now()
await next()
const interval = Date.now() - start
ctx.set('tt', `${ interval }ms`)
})
router.get('/', ctx => {
ctx.body = `
<html>
<head>
<title>hello</title>
</head>
<body>
<div id="app">${ content }</div>
</body>
</html>
`
})
app.use(router.routes())
app.use(async ctx => {
ctx.body = 'koa'
})
app.listen(3000, () => {
console.log('server deployed on port 3000...')
})
但是当我尝试启动我的服务器时,它只是告诉我:
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/ssr-plg/implessr/server/node_modules/react-dom/server' imported from /Users/ssr-plg/implessr/server/index.js
Did you mean to import react-dom/server.js?
这是我的 pkg.json:
{
"name": "server",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"license": "MIT",
"scripts": {
"start": "nodemon index.js"
},
"dependencies": {
"@koa/router": "^10.0.0",
"koa": "^2.13.1",
"react": "^17.0.1",
"react-dom": "^17.0.1"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
您可以在此repo中查看我的整个代码以获取详细信息。