1 | #!/usr/bin/env node
|
2 | const { fork } = require('child_process');
|
3 | const parse = require('yargs-parser');
|
4 | const chokidar = require('chokidar');
|
5 | const detect = require('detect-port');
|
6 | const path = require('path');
|
7 | const log = require('../dist/utils/log');
|
8 |
|
9 | let child = null;
|
10 | const rawArgv = parse(process.argv.slice(2));
|
11 | const scriptPath = require.resolve('./child-process-start.js');
|
12 | const configPath = path.resolve(rawArgv.config || 'build.json');
|
13 |
|
14 | const inspectRegExp = /^--(inspect(?:-brk)?)(?:=(?:[^:]+:)?(\d+))?$/;
|
15 |
|
16 | function 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 |
|
31 | function restartProcess() {
|
32 | (async () => {
|
33 |
|
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 |
|
50 | const onUserChange = () => {
|
51 | console.log('\n');
|
52 | log.info('build.json has been changed');
|
53 | log.info('restart dev server');
|
54 |
|
55 | process.env.RESTART_DEV = true;
|
56 | child.kill();
|
57 | restartProcess();
|
58 | };
|
59 |
|
60 | module.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 | };
|