-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
84 lines (70 loc) · 2.07 KB
/
index.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
80
81
82
83
84
const { access, copyFile, mkdir, stat, unlink } = require('fs/promises')
const path = require('path')
const chokidar = require('chokidar')
const glob = require('glob')
const globParent = require('glob-parent')
const { name } = require('./package.json')
require('colors')
const createDirIfNotExist = async destination => {
const dir = path.dirname(destination)
try {
await access(dir)
// eslint-disable-next-line no-unused-vars
} catch(e) {
await mkdir(dir, { recursive: true })
}
}
const prepareDestination = (from, entry) => {
const result = path.join(entry.dest, path.relative(globParent(entry.files), from))
return entry.rename ? result.replace(path.basename(result), entry.rename) : result
}
const copy = async (from, entry, verbose) => {
const data = await stat(from)
if (!data.isDirectory()) {
try {
const to = prepareDestination(from, entry)
await createDirIfNotExist(to)
await copyFile(from, to)
if (verbose)
console.log('[COPY]'.yellow, from, 'to'.yellow, to)
} catch (e) {
console.log('[COPY][ERROR]'.red, from)
console.error(e)
}
}
}
const remove = async (from, entry, verbose) => {
const to = prepareDestination(from, entry)
try {
await unlink(to)
if (verbose)
console.log('[DELETE]'.yellow, to)
} catch (e) {
console.log('[DELETE][ERROR]'.red, to)
console.error(e)
}
}
module.exports = (paths, { watch = process.env.ROLLUP_WATCH === 'true', verbose = false } = {}) => {
let once = true
return {
name,
buildStart() {
if (!once)
return
once = false
if (watch) {
for (const entry of paths) {
chokidar.watch(entry.files)
.on('add', from => copy(from, entry, verbose))
.on('change', from => copy(from, entry, verbose))
.on('unlink', from => remove(from, entry, verbose))
.on('error', e => console.error(e))
}
} else {
for (const entry of paths) {
glob.sync(entry.files).forEach(file => copy(file, entry, verbose))
}
}
}
}
}