UNPKG

1.91 kBJavaScriptView Raw
1#!/usr/bin/env node
2const { fork } = require('child_process');
3const parse = require('yargs-parser');
4const chokidar = require('chokidar');
5const detect = require('detect-port');
6const path = require('path');
7const log = require('../lib/utils/log');
8
9let child = null;
10const rawArgv = parse(process.argv.slice(2));
11const scriptPath = require.resolve('./child-process-start.js');
12const configPath = path.resolve(rawArgv.config || 'build.json');
13
14const inspectRegExp = /^--(inspect(?:-brk)?)(?:=(?:[^:]+:)?(\d+))?$/;
15
16function modifyInspectArgv(argv) {
17 return Promise.all(
18 argv.map(async item => {
19 const matchResult = inspectRegExp.exec(item);
20 if (!matchResult) {
21 return item;
22 }
23 const [_, command, ip, port = 9229] = matchResult;
24 const nPort = +port;
25 const newPort = await detect(nPort);
26 return `--${command}=${ip || ''}${newPort}`;
27 })
28 );
29}
30
31function restartProcess() {
32 (async () => {
33 // remove the inspect related argv when passing to child process to avoid port-in-use error
34 const argv = await modifyInspectArgv(process.execArgv);
35 child = fork(scriptPath, process.argv.slice(2), { execArgv: argv });
36 child.on('message', data => {
37 if (process.send) {
38 process.send(data);
39 }
40 });
41
42 child.on('exit', code => {
43 if (code) {
44 process.exit(code);
45 }
46 });
47 })();
48}
49
50const onUserChange = () => {
51 console.log('\n');
52 log.info('build.json has been changed');
53 log.info('restart dev server');
54 // add process env for mark restart dev process
55 process.env.RESTART_DEV = true;
56 child.kill();
57 restartProcess();
58};
59
60module.exports = () => {
61 restartProcess();
62
63 const watcher = chokidar.watch(configPath, {
64 ignoreInitial: true,
65 });
66
67 watcher.on('change', onUserChange);
68
69 watcher.on('error', error => {
70 log.error('fail to watch file', error);
71 process.exit(1);
72 });
73};