尝试服务器端呈现反应时得到 "Element type is invalid: expected a string"
got "Element type is invalid: expected a string" when trying to server side rendering react
我收到这个错误:
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
尝试使用 ReactDOMServer.renderToStaticMarkup
.
时
这是我的 React 应用程序:
"use strict";
import React from 'react'
module.exports = () => {
return (
<div></div>
);
};
这是我的节点服务器渲染代码:
"use strict";
const path = require('path');
const webpack = require('webpack');
const React = require('react'), ReactDOMServer = require('react-dom/server'),
DOM = React.DOM, body = DOM.body, div = DOM.div, script = DOM.script;
webpack({
target: "node",
entry: [
path.resolve(__dirname, '../js', 'app.js'),
],
module: {
loaders: [
{
exclude: /node_modules/,
loader: 'babel',
test: /\.js$/,
},
]
},
output: {filename: 'app.bundle.js', path: __dirname},
},() => {
const App = React.createFactory(require('./app.bundle.js'));
let html = ReactDOMServer.renderToStaticMarkup(body(null,
div({
id: 'root', dangerouslySetInnerHTML: {
__html: ReactDOMServer.renderToString(App())
}
})
));
});
有谁知道导致此错误的原因以及如何解决此问题?
提前致谢。
默认情况下,该包似乎与 commonjs 不兼容。正如我在 webpack docs 中读到的那样,您需要将 libraryTarget:'commonjs2'
添加到输出对象才能执行此操作。
像这样:
output: {filename: 'app.bundle.js', path: __dirname,libraryTarget:'commonjs2'}
我收到这个错误:
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
尝试使用 ReactDOMServer.renderToStaticMarkup
.
这是我的 React 应用程序:
"use strict";
import React from 'react'
module.exports = () => {
return (
<div></div>
);
};
这是我的节点服务器渲染代码:
"use strict";
const path = require('path');
const webpack = require('webpack');
const React = require('react'), ReactDOMServer = require('react-dom/server'),
DOM = React.DOM, body = DOM.body, div = DOM.div, script = DOM.script;
webpack({
target: "node",
entry: [
path.resolve(__dirname, '../js', 'app.js'),
],
module: {
loaders: [
{
exclude: /node_modules/,
loader: 'babel',
test: /\.js$/,
},
]
},
output: {filename: 'app.bundle.js', path: __dirname},
},() => {
const App = React.createFactory(require('./app.bundle.js'));
let html = ReactDOMServer.renderToStaticMarkup(body(null,
div({
id: 'root', dangerouslySetInnerHTML: {
__html: ReactDOMServer.renderToString(App())
}
})
));
});
有谁知道导致此错误的原因以及如何解决此问题?
提前致谢。
默认情况下,该包似乎与 commonjs 不兼容。正如我在 webpack docs 中读到的那样,您需要将 libraryTarget:'commonjs2'
添加到输出对象才能执行此操作。
像这样:
output: {filename: 'app.bundle.js', path: __dirname,libraryTarget:'commonjs2'}