forked from jestjs/jest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.js
79 lines (71 loc) · 2.03 KB
/
watch.js
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
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Watch files for changes and rebuild (copy from 'src/' to `build/`) if changed
*/
const {execSync} = require('child_process');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const chokidar = require('chokidar');
const {PACKAGES_DIR, getPackages} = require('./buildUtils');
const BUILD_CMD = `node ${path.resolve(__dirname, './build.js')}`;
let filesToBuild = new Map();
const exists = filename => {
try {
return fs.statSync(filename).isFile();
} catch {}
return false;
};
const rebuild = filename => filesToBuild.set(filename, true);
chokidar
.watch(
getPackages().map(p => path.resolve(p, 'src')),
{
ignoreInitial: true,
ignored: /(^|[\/\\])\../, // ignore dotfiles
},
)
.on('all', (event, filePath) => {
if (
(event === 'change' || event === 'rename' || event === 'add') &&
exists(filePath)
) {
console.log(
chalk.green('->'),
`${event}: ${path.relative(PACKAGES_DIR, filePath)}`,
);
rebuild(filePath);
} else {
filePath.split(path.join(path.sep, 'src', path.sep));
const buildFile = filePath
.replace(
path.join(path.sep, 'src', path.sep),
path.join(path.sep, 'build', path.sep),
)
.replace(/\.ts$/, '.js');
try {
fs.unlinkSync(buildFile);
process.stdout.write(
`${chalk.red(' \u2022 ')}${path.relative(
PACKAGES_DIR,
buildFile,
)} (deleted)\n`,
);
} catch {}
}
});
setInterval(() => {
const files = Array.from(filesToBuild.keys());
if (files.length) {
filesToBuild = new Map();
try {
execSync(`${BUILD_CMD} ${files.join(' ')}`, {stdio: [0, 1, 2]});
} catch {}
}
}, 100);
console.log(chalk.red('->'), chalk.cyan('Watching for changes...'));