capaj / require-globify

transform for browserify, which allows to require files with globbing expressions
MIT License
70 stars 11 forks source link

Usage with watchify #23

Open mdmoreau opened 8 years ago

mdmoreau commented 8 years ago

I'm trying to use require-globify to pull in a folder of individual modules. This works great with existing files, but when I add a new one to the module folder either watchify or require-globify isn't picking it up, so the bundle isn't updated.

Does this plugin support that type of configuration? I did notice that if I go back to the file with the require glob and save it then new files are pulled in. Any ideas?

call-a3 commented 8 years ago

Because require-globify itself doesn't watch any files or provide hints to other utilities which files/directories to watch, a tool like watchify can only watch the actual files that are being built into the bundle. The behaviour you're describing verifies this: when you edit the file with the glob-requirement, watchify detects the change in that file and rebuilds it, at which point require-globify gets another change at finding files (including new ones) that match the glob pattern.

I might be able to have watchify watch for changes on the globbed directories if I can detect that you're building using watchify and then hook into it. (IF this is at all possible, which I'd have to research.)

For now, you're probably gonna have to keep triggering a rebuild by editing the file with the glob.

mdmoreau commented 8 years ago

Thanks for the quick response, and I appreciate the useful transform! I thought that might be the case, so I sorted out a workaround for anyone who might have a similar usage.

If you're using gulp you can watch the files and trigger a resave of any files that have glob requires by using the watch/chokidar events along with gulp-savefile. It will resave the file(s) whenever a file is added or deleted.

var gulp = require('gulp');
var savefile = require('gulp-savefile');

function resave(src) {
  return gulp.src(src)
    .pipe(savefile());
};

var watcher = gulp.watch('src/js');

watcher.on('add', function() {
  resave('src/js/index.js');
});

watcher.on('unlink', function() {
  resave('src/js/index.js');
});
ba55ie commented 7 years ago

A bit late, but by using a watcher you can do something like this (based on the gulp recipe):

const gulp = require('gulp');
const gutil = require('gulp-util');
const watchify = require('watchify');
const browserify = require('browserify');
const source = require('vinyl-source-stream');

const b = watchify(browserify({
    entries: ['./src/js/index.js'],
    // Other config settings
}));

const bundle = () => b.bundle()
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./dist'));

b.on('update', bundle);
b.on('log', gutil.log);

// Watch and run bundler again when JS files are added or deleted
const watcher = gulp.watch('./src/js/subfolder/**/*.js');

watcher.on('add', bundle);
watcher.on('unlink', bundle);