backend.js 1.2 KB
Newer Older
J
Jason Park 已提交
1 2 3 4
const proxy = require('http-proxy-middleware');
const {
  __DEV__,
  proxyPort,
J
Jason Park 已提交
5
  backendBuildPath,
J
Jason Park 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
  apiEndpoint,
} = require('../environment');

if (__DEV__) {
  const webpack = require('webpack');

  const webpackConfig = require('../webpack.backend.config.js');

  const compiler = webpack(webpackConfig);

  let lastHash = null;
  let httpServer = null;
  compiler.watch({}, (err, stats) => {
    if (err) {
      lastHash = null;
      compiler.purgeInputFileSystem();
      console.error(err);
    }
    if (stats.hash !== lastHash) {
      lastHash = stats.hash;
      console.info(stats.toString({
        cached: false,
J
Jason Park 已提交
28
        colors: true
J
Jason Park 已提交
29 30 31 32
      }));

      try {
        if (httpServer) httpServer.close();
J
Jason Park 已提交
33 34
        delete require.cache[require.resolve('axios')];
        delete require.cache[require.resolve(backendBuildPath)];
J
Jason Park 已提交
35
        const app = require(backendBuildPath).default;
J
Jason Park 已提交
36 37 38 39 40 41 42
        httpServer = app.listen(proxyPort);
      } catch (e) {
        console.error(e);
      }
    }
  });
} else {
J
Jason Park 已提交
43
  const app = require(backendBuildPath).default;
J
Jason Park 已提交
44 45 46 47 48 49 50 51
  app.listen(proxyPort);
}

module.exports = proxy({
  target: `http://localhost:${proxyPort}/`,
  pathRewrite: { ['^' + apiEndpoint]: '' },
  ws: true,
});