0

尝试使用 Webpack 2 和 ReactJS.NET 编译 JSX 组件以进行服务器端渲染时,我收到以下错误消息:“模块构建失败:错误:最终加载程序未返回缓冲区或字符串”。我已按照此处以及此示例中描述的示例进行操作。

我的文件夹结构类似于 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;

/内容/组件/index.js

module.exports = {
    Test: require('./TestComponent.jsx')
}

/内容/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'
    }
}

我在这里创建了一个具有相同问题的示例项目。

4

1 回答 1

0

解决方案是取消 /Content/server.js 文件,而是使用 webpack 中的暴露加载器。这是更新的 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']
    }
}
于 2017-11-24T18:01:02.567 回答