Skip to content

Instantly share code, notes, and snippets.

@icavalheiro
Last active July 8, 2019 22:26
Show Gist options
  • Save icavalheiro/5a5ae22f1c856a9c3400fc25659ae52a to your computer and use it in GitHub Desktop.
Save icavalheiro/5a5ae22f1c856a9c3400fc25659ae52a to your computer and use it in GitHub Desktop.
Gulp file with watch and build that use parcel as the bundler (WEB)
const gulp = require('gulp');
const notifier = require('node-notifier');
const parcel = require('parcel-bundler');
const shell = require('shelljs');
function notifyError(err) {
notifier.notify({
title: 'Gulp detect an error',
message: 'Something broke! Please check console for logs!'
});
}
function getBaseOptions(isProduction) {
//we need to set the env because some plugins may depend on it
process.env.NODE_ENV = (isProduction) ? 'production' : 'dev';
return {
entryFiles: ['./frontend/index.html'],
outDir: './dist',
publicUrl: '/',
minify: isProduction,
hmr: false,
watch: !isProduction,
plugins: []
}
}
function cleanDistFolder(config) {
shell.rm('-rf', config.outDir);
}
function getBundler(config) {
var bundler = new parcel(config.entryFiles, config);
bundler.on('buildError', error => {
notifyError(error);
});
//customize the watch messages so they are easier to read
if (config.watch) {
bundler.on('buildStart', () => {
console.log('\x1b[2J');
console.log('\x1b[0f');
console.log('Building...');
});
}
//parcel when used as a API does not auto-discover the
//plugins, so we must initialize the plugins manually
//https://github.com/parcel-bundler/parcel/issues/3181
if (config.plugins & config.plugins.length) {
for (var i = 0; i < config.plugins.length; i++) {
var plugin = config.plugins[i];
plugin(bundler);
}
}
return bundler;
}
function watch() {
var config = getBaseOptions(false);
cleanDistFolder(config);
var bundler = getBundler(config);
bundler.bundle();
}
async function build(cb) {
var config = getBaseOptions(true);
cleanDistFolder(config);
var bundler = getBundler(config);
await bundler.bundle();
cb();
}
gulp.task('default', gulp.parallel(build));
gulp.task(build);
gulp.task(watch);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment