Я использую ReactDOMServer для рендеринга приложения, и я получил следующую ошибку:
У меня есть express в реакции машинописный проект. Что я делаю неправильно? Пожалуйста, помогите мне, спасибо.
Вот соответствующий код:
App.tsx
import * as React from 'react';
class App extends React.Component {
render() {
return (
<h1>Testing App Page</h1>
);
}
}
export default App
запись. 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);
});
middleware / 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>`
)
);
});
}