1 | const Browserify = require('browserify');
|
2 | const chalk = require('chalk');
|
3 | const fs = require('fs');
|
4 | const moment = require('moment');
|
5 | const R = require('ramda');
|
6 | const rm = require('rimraf');
|
7 | const Ru = require('@panosoft/ramda-utils');
|
8 | const Watchify = require('watchify');
|
9 |
|
10 | const options = R.merge(
|
11 | {
|
12 | standalone: 'report',
|
13 |
|
14 | builtins: false,
|
15 | commondir: false,
|
16 | detectGlobals: false,
|
17 | insertGlobalVars: '__filename,__dirname',
|
18 | browserField: false
|
19 | },
|
20 | Watchify.args
|
21 | );
|
22 | const browserify = Browserify(options);
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | const bundle = function (entry, options) {
|
34 | console.log('Options:', options);
|
35 | if (!entry) {
|
36 | var pkg;
|
37 | try {
|
38 | pkg = fs.readFileSync('./package.json');
|
39 | pkg = JSON.parse(pkg);
|
40 | }
|
41 | catch (error) { console.warn(chalk.yellow(error.message)); }
|
42 | if (pkg && pkg.main) entry = pkg.main;
|
43 | else entry = 'index.js';
|
44 | }
|
45 | options = Ru.defaults({
|
46 | output: 'bundle.js',
|
47 | watch: false
|
48 | }, options || {});
|
49 |
|
50 | console.log('Entry:', entry);
|
51 | console.log('Output:', options.output);
|
52 |
|
53 | browserify.add(entry);
|
54 |
|
55 | const bundle = () => {
|
56 | const filename = options.output;
|
57 | const handleError = error => {
|
58 | console.error(chalk.red(error.message));
|
59 | rm(filename, error => error ? console.error(chalk.red(error.message)) : null);
|
60 | };
|
61 | const stream = fs.createWriteStream(filename);
|
62 | stream.on('error', handleError);
|
63 | const bundle = browserify.bundle();
|
64 | bundle.on('error', handleError);
|
65 | bundle.pipe(stream);
|
66 | };
|
67 |
|
68 | if (options.watch) {
|
69 | const watchify = Watchify(browserify, {poll: true});
|
70 | watchify.on('log', (message) => {
|
71 | const timestamp = chalk.cyan(`[${moment().format('HH:mm:ss')}]`);
|
72 | console.log(timestamp, message);
|
73 | });
|
74 | watchify.on('update', bundle);
|
75 | }
|
76 |
|
77 | bundle();
|
78 | };
|
79 | module.exports = bundle;
|