summaryrefslogtreecommitdiffhomepage
path: root/gui/scripts/serve.js
blob: e1642c5b622db57afe1b8a29930d42ea05ea3f71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const { spawn } = require('child_process');
const path = require('path');
const TscWatchClient = require('tsc-watch/client');
const electron = require('electron');
const browserSync = require('browser-sync');
const browserSyncConnectUtils = require('browser-sync/dist/connect-utils');
const bsync = browserSync.create();

const getRootUrl = (options) => {
  const port = options.get('port');
  return `http://localhost:${port}`;
};

const getClientUrl = (options) => {
  const pathname = browserSyncConnectUtils.clientScript(options);
  return getRootUrl(options) + pathname;
};

function runElectron(browserSyncUrl) {
  const child = spawn(electron, ['.'], {
    env: {
      ...{
        NODE_ENV: 'development',
        BROWSER_SYNC_CLIENT_URL: browserSyncUrl,
      },
      ...process.env,
    },
    stdio: 'inherit',
  });
  child.once('close', () => {
    process.exit();
  });

  return child;
}

function startBrowserSync() {
  bsync.init(
    {
      ui: false,
      // Port 35829 = LiveReload's default port 35729 + 100.
      // If the port is occupied, Browsersync uses next free port automatically.
      port: 35829,
      ghostMode: false,
      open: false,
      notify: false,
      logSnippet: false,
      socket: {
        // Use the actual port here.
        domain: getRootUrl,
      },
    },
    (err, bs) => {
      if (err) return console.error(err);

      const browserSyncUrl = getClientUrl(bs.options);

      let child = runElectron(browserSyncUrl);

      bsync
        .watch(['build/src/config.json', 'build/src/main/**/*', 'build/src/shared/**/*'])
        .on('change', () => {
          child.removeAllListeners('close');
          child.once('close', () => {
            child = runElectron(browserSyncUrl);
          });
          child.kill();
        });

      bsync.watch(['build/src/renderer/**/*']).on('change', bsync.reload);
    },
  );
}

function prepareWatchArguments(projectPath) {
  return ['--noClear', '--sourceMap', '--project', projectPath];
}

const watch = new TscWatchClient();
watch.start(...prepareWatchArguments(path.resolve(__dirname, '..')));
watch.on('first_success', () => {
  startBrowserSync();
});