我只是想用 react 和 create-react-app 启用服务器端渲染。
我已经编写了一个服务器/索引.js文件,该文件应该以字符串形式返回一个简单的反应组件。
//require('import-export');
//require('babel-register')({ ignore: //(build|node_modules)//, presets: ['react-app', 'es2015', 'react'] });
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const fs = require('fs');
const index = require('./index.js');
const react = require('react');
const reactServerDom = require('react-dom/server');
const renderToString = reactServerDom.renderToString;
const ourComponent = require('../src/App.js');
const app = express();
// Setup logger
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));
// Serve static assets - NEEDS TO BE ACTIVATED LATER WHEN RENDERTOSTRING WORKS!
//app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.get('/', (req, res) => {
const filePath = path.resolve(__dirname, '..', 'build', 'index.html');
let result = '';
fs.readFile(filePath, 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
const ReactApp = renderToString(react.createElement(ourComponent));
result = data.replace('{{SSR}}', ReactApp);
res.send(result);
});
});
const port = 9007;
app.listen(port, () => {
console.log(`App listening on port ${ port }`);
});
module.exports = app;
应该渲染的组件只是每个人都从create-react-app获得的示例组件:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
在我的 package.json 中,我有以下命令使用命令 yarn 服务器或 npm run 服务器启动带有 babel-node 的服务器:
...
"scripts": {
"start": "react-scripts start",
"server": "NODE_ENV=development babel-node --presets=es2015,react server/index.js",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
...
但我仍然收到以下错误:
$ NODE_ENV=development babel-node --presets=es2015,react server/index.js
/home/sonnenfeld/ssr-render/src/logo.svg:4
React.createElement(
^
ReferenceError: React is not defined
如果我从组件中删除 svg,我会收到另一个错误:
SyntaxError: /home/sonnenfeld/ssr-render/src/App.css: Unexpected token (1:0)
> 1 | .App {
| ^
2 | text-align: center;
3 | }
4 |
我已经尝试过带有 babel 寄存器的 babel 钩子,但也没有成功。
当使用带有 express 的 create-react-app 时.js转译我的服务器和所有依赖项到原版 javascript 的好方法是什么?
服务器端渲染可能非常困难。所以我完全切换到 next-js。
样式化组件的问题已通过官方解决方法 https://www.styled-components.com/docs/advanced#server-side-rendering 解决