我正在收到以下错误 - '模块构建失败:错误:最终加载程序在尝试编译用于使用WebPack 2的服务器端渲染的JSX组件时未返回缓冲区或字符串'和reactjs.net。我遵循了此处所述的示例以及此示例。
我的文件夹结构类似于github示例,我有一个react组件,一个index.js文件和一个server.js文件。这是内容:
/content/components/testcomponent.jsx
var React = require('react');
class Test extends React.Component {
getInitialState() {
return { data: this.props.greeting };
}
render() {
return (
<div>
<h1>{this.props.greeting}</h1>
</div>);
}
}
module.exports = Test;
/content/components/index.js
module.exports = {
Test: require('./TestComponent.jsx')
}
/content/server.js
var Components = require('expose?Components!./components');
这是我的完整webpack.config.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './Content/server',
output: {
path: __dirname + '/resources/dev/scripts/server',
filename: 'test.js'
},
module: {
rules: [
{
test: /.js$|.jsx$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env', 'react'],
}
}
{
test: require.resolve('react'),
loader: 'expose?React'
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
externals: {
react: 'React'
}
}
我在这里创建了一个示例项目,却有相同的问题。
解决方案是消除/content/server.js文件,而是在webpack中使用expose-loader。这是更新的webpack.config.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './Content/components/index',
output: {
path: __dirname + '/resources/dev/scripts/server',
filename: 'test.js'
},
module: {
rules: [
{
test: /.js$|.jsx$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env', 'react'],
}
},
{
test: require.resolve('./Content/components/index'),
use: [{
loader: 'expose-loader',
options: 'Components'
}]
},
{
test: require.resolve('react'),
use: [{
loader: 'expose-loader',
options: 'React'
}]
}
]
},
resolve: {
extensions: ['.js', '.jsx']
}
}