Why do we need a proxy on an express.js server in order to get webpack hot reloading server functionality combined with react-routing

為{幸葍}努か 提交于 2019-12-04 07:35:26

You don't, but it's tricky. So the first requirement is that you have a configurable asset root. This also pays off if you need a CDN in the future. Let's say this is in an envvar ASSET_URL which is available both when running your webpack dev server and your express server.

You need the usual webpack dev server, plus the CORS header. This lets your main express server just point to the webpack dev server in the script/link tags.

ASSET_URL is like: http://localhost:8081

Webpack

var config = require('./webpack.config');

var port = '8081', hostname = 'localhost';

if (process.env.ASSETS_URL) {
    var assetUrlParts = url.parse(process.env.ASSETS_URL);
    port = assetUrlParts.port;
    hostname = assetUrlParts.hostname;
}

new WebpackDevServer(webpack(serverConfig), {
  publicPath: serverConfig.output.publicPath,
  hot: true,
  headers: { "Access-Control-Allow-Origin": "*" }
}).listen(port, 'localhost', function (err, result) {
  if (err) {
    console.log(err);
    process.exit(1);
  }

  console.log('Listening at ' + url.format({port: port, hostname: hostname, protocol: 'http:'}));
});

Then in your webpack config file you have most of the same junk.

var port = '8081', hostname = 'localhost';

if (process.env.ASSETS_URL) {
    var assetUrlParts = url.parse(process.env.ASSETS_URL);
    port = assetUrlParts.port;
    hostname = assetUrlParts.hostname;
}

...

  entry: [
    'webpack-dev-server/client?' + url.format({port: port, hostname: hostname, protocol: 'http:'}),
    'webpack/hot/only-dev-server',
    ...

  output: {
    path: __dirname + '/public/',
    filename: 'bundle.js',
    publicPath: process.env.ASSETS_URL || '/public/'

Express Server

The only special thing here is you need to somehow get process.env.ASSETS_URL into the locals of your templates.

<head>
    <link rel="stylesheet" href="{{ assetsUrl }}/main.css">
</head>
<body>
    ...
    <script type="text/javascript" src="{{ assetsUrl }}/bundle.js"></script
</body>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!