使用Webpack Express和React进行服务器端渲染

问题描述 投票:1回答:2

我正在尝试学习React,在尝试运行我的配置以进行React服务器端渲染的许多尝试之后,我将代码简化为最简单的示例,但是我仍然不明白为什么它不起作用。

案子

我的控制器:

$router = $container->get(Router::class);
$router->get('/test/{name:.*}', function ($request) use ($container) {
    /** @var $request \GuzzleHttp\Psr7\ServerRequest **/
    $client = new Client(['base_uri' => 'http://localhost:3000']);
    $response = $client->post('/', [
        'query' => ['module' => 'App'],
    ]);
    $contents = $response->getBody()->getContents();

    return $contents;
});

我正在使用GuzzleHttp库

我的服务器配置:

/path/to/project/resources/server.js => /path/to/project/server.js

import express from 'express'
import React from 'react'
import ReactDOMServer from 'react-dom/server'

let app = express()

app.use('/', (request, response) => {
  try {
    let App = require('../public/dist/js/' + request.query.module)
    response.send(
      ReactDOMServer.renderToString(<App/>)
    )
  } catch (error) {
    response.status(500).send(error.message)
  }
})

app.listen(3000)

我的组件

/path/to/project/resources/assets/js/App.jsx => /path/to/project/public/dist/js/App.js

import React from 'react';

class App extends React.Component {
  render () {
    return <h1>Hello World!</h1>;
  }
}

module.exports = App;

我的webpack配置

const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJsPlugin = require ('uglifyjs-webpack-plugin');

function assets(path) {
  return './resources/assets/' + path;
}

const config = {
  entry: [
    assets('js/App.jsx'),
    assets('sass/app.scss')
  ],
  output: {
    path: path.resolve(__dirname, 'public/dist'),
    filename: 'js/App.js',
    publicPath: '/dist/'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      { // es2015
        test: /\.(js|jsx)/,
        use: ['babel-loader'],
        exclude: [/node_modules/]
      },
      { // css / sass / scss loaders
        test: /\.(css|sass|scss)$/,
        use: ExtractTextPlugin.extract({
          use: ['css-loader', 'sass-loader'],
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({
      filename: 'css/[name].bundle.css',
      allChunks: true
    }),
    new UglifyJsPlugin()
  ]
};

const server = {
  entry: [
    './resources/server.js'
  ],
  output: {
    path: path.resolve(__dirname, '.'),
    filename: 'server.js',
    publicPath: '/dist/'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      { // es2015
        test: /\.(js|jsx)/,
        use: ['babel-loader'],
        exclude: [/node_modules/]
      }
    ]
  },
  plugins: [
    //new UglifyJsPlugin()
  ],
  target: 'node'
};

module.exports = [config, server];

Babelrc配置

{
  "presets": ["es2015", "react"]
}

结果

  1. 我与Guzzle碰到错误

500 Internal Server Error响应:element.type.toLowerCase不是函数

  1. 我收到nodeJS错误

警告:React.createElement:类型无效-预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到了:对象。 您可能忘记了从定义文件中导出组件,或者可能混淆了默认导入和命名导入。 在未知

  1. 捆绑文件后会得到什么:

Webpack输出

我尝试了很多不同的方法,但是我不明白为什么这会引发错误。


编辑:

使用此配置,我可以使事情正常运行,问题似乎出在导入部分:

import express from 'express'
import * as React from 'react'
import ReactDOMServer from 'react-dom/server'

let app = express()

class App extends React.Component {
  render () {
    return <h1>Hello World!</h1>;
  }
}

const component = <App />;

app.use('/', (request, response) => {
  try {
    response.send(
      ReactDOMServer.renderToString(component)
    )
  } catch (error) {
    response.status(500).send(error.message)
  }
})

app.listen(3000)

编辑2:

这是我从.npm检索到的日志

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'start' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle [email protected]~prestart: [email protected]
6 info lifecycle [email protected]~start: [email protected]
7 verbose lifecycle [email protected]~start: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]~start: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/dev/www/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
9 verbose lifecycle [email protected]~start: CWD: /home/dev/www
10 silly lifecycle [email protected]~start: Args: [ '-c', 'node server.js' ]
11 silly lifecycle [email protected]~start: Returned: code: 1  signal: null
12 info lifecycle [email protected]~start: Failed to exec start script
13 verbose stack Error: [email protected] start: `node server.js`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:285:16)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at EventEmitter.emit (events.js:214:7)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at ChildProcess.emit (events.js:214:7)
13 verbose stack     at maybeClose (internal/child_process.js:925:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid [email protected]
15 verbose cwd /home/dev/www
16 verbose Linux 4.9.0-4-amd64
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "start"
18 verbose node v8.9.4
19 verbose npm  v5.6.0
20 error code ELIFECYCLE
21 error errno 1
22 error [email protected] start: `node server.js`
22 error Exit status 1
23 error Failed at the [email protected] start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
php node.js reactjs webpack serverside-rendering
2个回答
0
投票

在您的组件中尝试。

import * as React from 'react';

class App extends React.Component {
  render () {
    return <h1>Hello World!</h1>;
  }
}

module.exports = App;

可能只是从react包中获取默认导出。


0
投票

默认情况下,Webpack不会像您期望的那样输出CommonJS导出。

您可以尝试添加

output: {
  ....
  library: 'server',
  libraryTarget: 'commonjs2'
}

target: 'node'

到Webpack中的输出模块。 并且,以防万一您想导入任何sass(或App.js中的任何其他文件),请确保相对于它们的源引用了它们。 它们将被捆绑在创建的捆绑包中。 因此,请勿在您的条目中包含App.sass。

希望能有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.