3

Whenever I change function.js, I have to manually run the command below to browserify function.js into a bundle.js

$ browserify function.js --standalone function > bundle.js

How can this step be automated such that the command is run automatically in the background whenever function.js is modified?

I am using node.js v6.9 with Webstorm 2016.2 on Windows 10.

guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • 1
    Have a look at the gulp and grunt sections of this answer: [What are npm, bower, gulp, Yeoman, and grunt good for?](http://stackoverflow.com/a/36789515/3993662). Apart from that, you can create a file watcher in webstorm. Simply type watchers in the search all dialog – baao Nov 13 '16 at 13:15
  • https://confluence.jetbrains.com/display/PhpStorm/File+Watchers+in+PhpStorm – LazyOne Nov 13 '16 at 16:22

2 Answers2

4

This is very easy with watchify, Just install npm i -D watchify

then update your 'package.json' file with a command "watch" : "npx watchify <source>.js -o <output>.js"

And your are ready to go with just running your npm command npm run watch.

Pranta Saha
  • 711
  • 1
  • 8
  • 12
2

The browserify command you want to run is;

$ browserify function.js --standalone function > bundle.js

Taking reference from https://github.com/gulpjs/gulp/blob/master/docs/recipes/fast-browserify-builds-with-watchify.md

Here is the full code for what you need. Only slight modification from the reference code is needed for the opts to Browserify.

'use strict';

var watchify = require('watchify');
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var assign = require('lodash.assign');

// add custom browserify options here
var customOpts = {
  entries: ['./function.js'],
  standalone: 'function',
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts)); 

// add transformations here
// i.e. b.transform(coffeeify);

gulp.task('js', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal

function bundle() {
  return b.bundle()
    // log errors if they happen
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    // optional, remove if you don't need to buffer file contents
    .pipe(buffer())
    // optional, remove if you dont want sourcemaps
    .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
       // Add transformation tasks to the pipeline here.
    .pipe(sourcemaps.write('./')) // writes .map file
    .pipe(gulp.dest('./dist'));
}
guagay_wk
  • 26,337
  • 54
  • 186
  • 295