-
Notifications
You must be signed in to change notification settings - Fork 2
/
watch.js
65 lines (58 loc) · 2.08 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
const fs = require('fs')
const spawn = require('child_process').spawn
const babel = require('babel-core')
require('colors')
const pkg = JSON.parse(fs.readFileSync('package.json'))
console.log(`\nWatching ${pkg.name} v${pkg.version}\n`.underline.bold)
const build = spawn('yarn', ['run', 'build'])
build.on('close', code => console.log('Initial build ready\n'.grey)) // ready
build.on('error', error => console.log(error))
const fileChanged = function (filename) {
if (filename.endsWith('.less')) {
const build = spawn('yarn', ['run', 'build-styles'])
setTimeout(() => {
const result = fs.readFileSync('./lib/styles.css')
fs.writeFileSync('./lib/styles.css', result + '\n')
}, 1000)
build.on('error', error => console.log(error))
} else if (filename.endsWith('.js')) {
try {
const result = babel.transformFileSync('./src/' + filename).code
fs.writeFileSync('./lib/' + filename, result)
} catch (error) {
console.log(error.message.red + '\n')
if (error._babel) {
console.log(error.codeFrame)
console.log('')
} else {
console.log(error)
}
}
} else if (fs.lstatSync('./src/' + filename).isDirectory()) {
fs.mkdirSync('./lib/' + filename)
fs.readdirSync('./src/' + filename).forEach(file => {
fileChanged(filename + '/' + file)
console.log(filename.grey + '/' + file)
})
}
}
const deleteFile = function (filename) {
if (fs.lstatSync(filename).isDirectory()) {
fs.readdirSync(filename).forEach(file => deleteFile(filename + '/' + file))
fs.rmdirSync(filename)
} else {
fs.unlinkSync(filename)
}
}
const fileEvent = function (eventType, filename) {
const existsInLib = fs.existsSync('./lib/' + filename)
const existsInSrc = fs.existsSync('./src/' + filename)
const action = eventType === 'rename' ? !existsInSrc ? 'deleted' : 'created' : 'changed'
console.log(filename.bold + ` ${action}`.grey)
if (action === 'deleted' && existsInLib) {
deleteFile('./lib/' + filename)
} else {
fileChanged(filename)
}
}
fs.watch('./src', {recursive: true}, fileEvent)