使用热模块重新加载来反应服务器端呈现

时间:2017-02-08 17:56:10

标签: reactjs webpack webpack-hmr ssr

我一直在做很多阅读,似乎github上有很多可用的样板,它们都可以使用webpack-dev-server来重建客户端捆绑包。但是,我不确定服务器是如何或是否重新加载热模块。有没有办法配置webpack在服务器端启用HMR?否则,似乎我更改的任何内容都不会由服务器呈现,只会在客户端刷新。

我的webpack配置看起来像这样:

module.exports = {
  entry: "./js/client.js",
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
        }
      }
    ]
  },
  output: {
    path: __dirname + "/public/",
    filename: "client.min.js"
  }
};

server.js:

app.get('/', function(request, response) {
  var html = ReactDOMServer.renderToString(React.createElement(Component));
  response.send(html);
});

Component.js:

module.exports = React.createClass({
  _handleClick: function() {
    alert();
  },

  render: function() {
    return (
      <html>
        <head>
          <title>{this.props.title}</title>
          <link rel="stylesheet" href="/style.css" />
        </head>
        <body>
          <h1>{this.props.title}</h1>
          <p>isn't server-side rendering remarkable?</p>
          <button onClick={this._handleClick}>Click me</button>
          <script dangerouslySetInnerHTML={{
            __html: 'window.PROPS=' + JSON.stringify(this.props)
          }} />
          <script src="/client.min.js" />
        </body>
      </html>
    );
  }
})

和client.js:

var props = window.PROPS;

ReactDOM.render(React.createElement(Component, props), document);

我使用webpack-dev-server --content-base src --inline --hot来运行webpack

1 个答案:

答案 0 :(得分:1)

您希望通过server.js运行代码。在package.json中创建一个脚本来运行该文件。

例如:

"serve":"nodemon server.js"

然后,添加webpack-dev-server webpack-dev-middlewarewebpack-hot-middlware的替代方案,它可以帮助您HMR

这就是server.js的样子:

import express from 'express';
import webpack from 'webpack';
import path from 'path';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';

const port = 5000;
const app = express();
const config = require(path.resolve("./webpack.config.js"));

const compiler = webpack(config);

app.use(webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath,
}));

app.use(webpackHotMiddleware(compiler));

app.get("*", function(req, res, next) {
    res.sendFile( path.join( __dirname, '/path/to/your/index.html') );
});

app.listen(port, function(err) {
    if(err) {
        return console.log(err);
    }
    return console.log(`App is now running on http://localhost:${port}`);
});

然后,运行您的脚本,如下所示:

npm run serve

只需访问浏览器上的端口,您的客户端就会显示出来。

希望这有帮助。