-
Notifications
You must be signed in to change notification settings - Fork 143
/
copy-and-watch.mjs
64 lines (61 loc) · 2.24 KB
/
copy-and-watch.mjs
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
import fs from 'fs';
import path from 'path';
// custom plugin to copy files and watch them
export default function copyAndWatch(config) {
const resolvedConfig = {
targets: []
};
// resolve source directories into files
config.targets.forEach(target => {
const readRec = pathname => {
if (!fs.existsSync(pathname)) {
console.log(`skipping missing file ${target.src}`);
} else {
if (fs.lstatSync(pathname).isDirectory()) {
const children = fs.readdirSync(pathname);
children.forEach(childPath => {
readRec(path.join(pathname, childPath));
});
} else {
let dest;
if (fs.lstatSync(target.src).isDirectory()) {
dest = path.join(
target.dest || '',
path.basename(target.destFilename || target.src),
path.relative(target.src, pathname)
);
} else {
dest = path.join(target.dest || '', path.basename(target.destFilename || target.src));
}
resolvedConfig.targets.push({
src: pathname,
dest: dest,
transform: target.transform
});
}
}
};
readRec(target.src);
});
return {
name: 'copy-and-watch',
async buildStart() {
// disable watching during production build
if (process.env.NODE_ENV !== 'production') {
resolvedConfig.targets.forEach(target => {
this.addWatchFile(target.src);
});
}
},
async generateBundle() {
resolvedConfig.targets.forEach(target => {
const contents = fs.readFileSync(target.src);
this.emitFile({
type: 'asset',
fileName: target.dest,
source: target.transform ? target.transform(contents, target.src) : contents
});
});
}
};
}