我正在尝试连接一个最小的概念验证,以呈现单个React组件服务器端。
当我运行我的应用程序时,出现错误:
SyntaxError: express.js: Unexpected token (10:41)
违规行是:
> 10 | res.send(ReactDOMServer.renderToString(<Component msg={msg} />));
| ^
这是我的package.json
:
{
"name": "ssrReact",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "nodemon express.js --exec babel-node --presets es2015,stage-2"
},
"dependencies": {
"express": "^4.14.1",
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"babel-cli": "^6.22.2",
"babel-preset-es2015": "^6.22.0",
"babel-preset-stage-2": "^6.22.0",
"nodemon": "^1.11.0"
}
}
这是我的Component.js
:
import React from 'react';
class Component extends React.Component {
render() {
return <h1>Hello, {this.props.msg}</h1>;
}
}
export default Component;
这是我的express.js
:
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Component from './Component';
const app = express();
function home (req, res) {
const msg = req.params.msg || 'Hello';
res.send(ReactDOMServer.renderToString(<Component msg={msg} />));
}
app.get('/', home);
app.get('/:msg', home);
app.listen(3333);
为了让Express能够提供React组件,我需要更改什么?
感谢您的帮助。
答案 0 :(得分:3)
我的两分钱,做:
npm i -D babel-preset-react
将您的运行脚本更改为:
"scripts": {
"start": "nodemon express.js --exec babel-node --presets es2015,stage-2,react"
},
要解析 jsx ,您需要安装babel-preset-react