UNPKG

1.99 kBJavaScriptView Raw
1import browserify from 'browserify'
2import chalk from 'chalk'
3import fs from 'fs'
4import rollupify from 'rollupify'
5import watchify from 'watchify'
6
7let watchError
8export default function watch(opts) {
9 const b = browserify({
10 cache: {},
11 // debug: true,
12 entries: [opts.entry],
13 packageCache: {},
14 plugin: [watchify]
15 })
16
17 const domain = chalk.dim(`[${opts.domain}${opts.root}]`)
18
19 // entry point of our app, panels needs this to require it
20 b.require(opts.entry, {expose: opts.expose})
21
22 // expose the app dependencies
23 b.require(opts.requires)
24
25 // rollupify the bundle
26 b.transform(rollupify, {config: opts.rollupConfig, sourceMaps: false})
27
28 // declare our build's externals
29 opts.externals.forEach(dep => b.external(dep))
30
31 // run the bundle and output to the console
32 function bundle() {
33 b.bundle().pipe(fs.createWriteStream(opts.tmp))
34 }
35 bundle()
36
37 b.on('update', bundle)
38 b.on('log', msg => {
39 console.log(domain, msg)
40 })
41
42 b.on('bundle', theBundle => {
43 theBundle.on('error', error => {
44 if (watchError !== error.stack) {
45 if (error.codeFrame) {
46 console.error(domain, chalk.red(`${error.constructor.name} at ${error.id}`))
47 console.error(domain, error.codeFrame)
48 } else {
49 const match = error.stack.match(/Error: Could not resolve (.+?) from (.+?) while/)
50 if (match) {
51 console.error(domain, chalk.red(`ImportError at ${match[2]}`))
52 console.error(domain, 'Does', chalk.blue(match[1]), 'exist? Check that import statement.')
53 } else {
54 console.error(domain, error.stack)
55 }
56 }
57 watchError = error.stack
58 }
59 b.removeAllListeners()
60 b.close()
61 setTimeout(() => watch(opts), 1000)
62 })
63 })
64
65 return function cleanup() {
66 try {
67 fs.unlinkSync(opts.tmp)
68 } catch(err) {
69 }
70
71 try {
72 fs.unlinkSync(`${opts.entry}.tmp`)
73 } catch(err) {
74 }
75 process.exit()
76 }
77}