【发布时间】:2020-06-24 01:56:37
【问题描述】:
我正在使用 ReactDOMServer 渲染应用程序,但出现以下错误:
我已经在 react typescript 项目中设置了 express。我究竟做错了什么?请帮帮我,谢谢。
以下是相关代码:
App.tsx
import * as React from 'react';
class App extends React.Component {
render() {
return (
<h1>Testing App Page</h1>
);
}
}
export default App
entry.js
require('ignore-styles');
require("@babel/register")({
ignore: [ /(node_modules)/ ],
presets: [[
"@babel/preset-env",
{
"targets": {
"esmodules": true
}
}
], '@babel/preset-react']
});
require('./index');
index.js
import express from 'express';
import serverRenderer from './middleware/renderer';
const PORT = 3000;
const path = require('path');
const app = express();
const router = express.Router();
router.use('^/$', serverRenderer);
// other static resources should just be served as they are
router.use(express.static(
path.resolve(__dirname, '..', 'build'),
{ maxAge: '1d' },
));
app.use(router);
app.listen(PORT, (error) => {
console.log("App port listen on ", PORT);
});
中间件/renderer.js
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import App from '../../src/App';
// const App = require("../../src/App"); <= also try this but not work
const path = require("path");
const fs = require("fs");
export default (req, res, next) => {
// point to the html file created by CRA's build tool
const filePath = path.resolve(__dirname, '..', '..', 'build', 'index.html');
fs.readFile(filePath, 'utf8', (err, htmlData) => {
if (err) {
console.error('err', err);
return res.status(404).end()
}
// render the app as a string
const html = ReactDOMServer.renderToString(React.createElement(<App />));
// inject the rendered app into our html and send it
return res.send(
htmlData.replace(
'<div id="root"></div>',
`<div id="root">${html}</div>`
)
);
});
}
【问题讨论】:
标签: node.js reactjs typescript react-router