我正在尝试使用ES6模块语法来对React组件进行SSR,但无法使其正常工作。我使用express生成器创建了一个express应用,并创建了一个简单的Component:
import React from 'react';
const Test = (props) => {
return (
<h1>Testing 1, 2, 3!</h1>
);
}
export default Test;
存储在components / Test.jsx中
然后,在routes / index.js中:
var express = require('express');
var router = express.Router();
const React = require('react');
const ReactDOMServer = require('react-dom/server');
// Transpile and add the React Component
require("@babel/register")({
presets: [
'@babel/preset-react',
'@babel/preset-env'
]
});
const Test = React.createFactory(require('../components/Test.jsx'));
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express',
component: ReactDOMServer.renderToString(Test()) });
});
module.exports = router;
所以我将@ babel / register用作babel的require()
钩子。 preset-react
用于JSX,preset-env
用于ES6。但是我得到的是:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
如果我将CommonJS与Component一起使用,则可以正常工作。但是ES6,不。有什么想法吗?