我正在尝试将使用CRA创建的react应用转换为服务器渲染,并按照教程开始使用以下配置:
my-app / server / 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);
router.use(express.static(path.resolve(__dirname, '..', 'build'), { maxAge: '30d' }));
app.use(router);
app.listen(PORT, (error) => {
if (error) {
return console.log('something bad happened', error);
}
console.log('listening on ' + PORT + '...');
});
my-app / server / middleware / renderer.js:
import React from 'react';
import ReactDOMServer from 'react-dom/server';
// import our main App component
import App from '../../src/views/App';
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(<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>`)
);
});
};
my-app / server / bootstrap.js:
require('ignore-styles');
require('@babel/register')({
ignore: [/(node_modules)/],
presets: ['@babel/preset-env', '@babel/preset-react']
});
require('./index');
我使用node server/bootstrap.js
启动服务器,并收到以下错误消息:Error: Cannot find module '../constants/RouteEnum'
。这来自我在import App
中所做的renderer.js
。我强调此模块存在并且可以正常工作(如果我只运行npm start
,就没有问题,该应用程序已在浏览器中加载,没有任何错误),但是由于某种原因,我的服务器无法从其来源正确解释
有人猜想如何解决该问题吗?