UNPKG

2.12 kBJavaScriptView Raw
1const Browserify = require('browserify');
2const chalk = require('chalk');
3const fs = require('fs');
4const moment = require('moment');
5const R = require('ramda');
6const rm = require('rimraf');
7const Ru = require('@panosoft/ramda-utils');
8const Watchify = require('watchify');
9
10const options = R.merge(
11 {
12 standalone: 'report',
13 // api options set by the `--node` cli option
14 builtins: false,
15 commondir: false,
16 detectGlobals: false,
17 insertGlobalVars: '__filename,__dirname',
18 browserField: false
19 },
20 Watchify.args
21);
22const browserify = Browserify(options);
23/**
24 * Bundle a module and its dependencies into a single file.
25 *
26 * @params {String} [entry]
27 * If entry is not supplied, the package.json `main` property will be used.
28 * If that is blank, then `index.js` will be used
29 * @params {Object} [options]
30 * @params {String} [options.output=bundle.js]
31 * @params {Boolean} [options.watch=false]
32 */
33const 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};
79module.exports = bundle;