Skip to content

Instantly share code, notes, and snippets.

@LoganBarnett
Last active September 18, 2015 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LoganBarnett/8b499b0aa94994fde0dd to your computer and use it in GitHub Desktop.
Save LoganBarnett/8b499b0aa94994fde0dd to your computer and use it in GitHub Desktop.
Gulp file for doing lots of cool stuff I want in all of my projects.
/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Logan Barnett (logustus@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*******************************************************************************/
'use strict';
const gulp = require('gulp');
const concat = require('gulp-concat');
const browserSync = require('browser-sync').create();
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const babelify = require('babelify');
const watchify = require('watchify');
const R = require('ramda');
const gutil = require('gulp-util');
const karma = require('karma');
const jasmine = require('gulp-jasmine');
const notify = require('gulp-notify');
const nodemon = require('nodemon');
const sass = require('gulp-sass');
const fs = require('fs');
const del = require('del');
const cssModulesify = require('css-modulesify');
const revHash = require('rev-hash');
const getConfig = (existsFn) => {
if(existsFn()) {
return JSON.parse(fs.readFileSync('local.gulp.json', {encoding: 'utf-8'}));
}
else {
return defaultConfig;
}
};
const defaultConfig = {
clientBuildDir: 'dist'
, tempDir: '.tmp'
};
const config = getConfig(R.partial(fs.existsSync, './local.gulp.json'));
const handleError = (task) => {
return (err) => {
gutil.log(gutil.colors.red(err));
// what logs exactly?...
notify.onError(task + ' failed, check logs...')(err);
}
};
const runStyles = () => {
return gulp.src(['./client/styles/main.scss', './client/styles/other.scss'])
.pipe(sass({
outputStyle: 'nested'
, includePaths: ['./client/node_modules/bootstrap-sass/assets/stylesheets']
})
.on('error', sass.logError))
.pipe(gulp.dest('client/app/.tmp/css'))
;
};
const promiseMoveFile = (transform) => {
const p = new Promise((resolve, reject) => {
const t = R.mapObj((x) => config.clientBuildDir + '/' + x, transform);
fs.rename(t.old, t.new, (err) => {
if(err) {
reject(
'Error moving file from "'
+ transform.old + '" to "'
+ transform.new + '": ' + err);
}
else {
resolve();
}
});
});
return p;
};
const promiseFileWrite = (path, data) => {
const p = new Promise((resolve, reject) => {;
fs.writeFile(path, data, (writeError) => {
if(writeError) {
reject('Error writing hash to index.html: ' + writeError);
}
else {
resolve();
}
});
});
return p;
};
const promiseFileHash = (revHash, path) => {
const p = new Promise((resolve, reject) => {
fs.readFile(path, (jsError, buffer) => {
if(jsError) {
reject('Error reading app.min.js: ' + jsError);
}
else {
resolve(revHash(buffer));
}
});
});
return p;
};
const promiseFileData = (read, file) => {
const p = new Promise((resolve, reject) => {
read(file, 'utf8', (readError, fileData) => {
if(readError) {
reject('Error reading file "' + file + '":' + readError);
}
else {
resolve(fileData);
}
});
});
return p;
};
const transformText = (text, transforms) => {
return R.reduce(
(text, t) => text.replace(t.old, t.new)
, text
, transforms
);
};
gulp.task('host:all', ['host:main', 'host:browser-sync']);
gulp.task('host:browser-sync', ['build-and-watch', 'styles', 'static:watch', 'static:copy', 'watch-client-test', 'browser-sync']);
gulp.task('watch-server-test', () => {
if(!fs.existsSync('./server/app.js')) {
gutil.log('No server script found. Refusing to watch server tests.');
return;
}
return gulp.watch('./server/**/*.spec.js', ['test:server']);
});
gulp.task('watch-client-test', (done) => {
// karma handles the watch part
var server = new karma.Server({
configFile: __dirname + '/karma.conf.js'
, singleRun: false
}, done);
server.start();
});
gulp.task('test:client', (done) => {
var server = new karma.Server({
configFile: __dirname + '/karma.conf.js'
, singleRun: true
}, done);
server.start();
});
gulp.task('test:server', () => {
return gulp.src('./server/**/*.spec.js')
//.pipe(babel())
.pipe(jasmine({includeStackTrace: true}))
//.pipe(mocha({compilers: {js: babelRegister}}))
;
});
gulp.task('clean', () => {
return gulp.src(config.clientBuildDir, {read: false})
.pipe(del())
;
});
gulp.task('styles', () => {
return runStyles();
});
gulp.task('styles:reload', ['styles'], (done) => {
browserSync.reload();
done();
});
gulp.task('static:copy', () => {
return gulp.src(['client/assets/**/*', 'node_modules/babel-core/browser-polyfill.js'])
.pipe(gulp.dest(config.clientBuildDir))
;
});
gulp.task('static:reload', ['static:copy'], (done) => {
browserSync.reload();
done();
});
gulp.task('static:index:copy', () => {
return gulp.src(['client/index.html'])
.pipe(gulp.dest(config.clientBuildDir))
;
});
gulp.task('static:index:rev', ['static:index:copy'], (done) => {
try {
const indexPath = config.clientBuildDir + '/index.html';
const promiseRev = R.partial(promiseFileHash, revHash);
const promises = [
promiseRev(config.clientBuildDir + '/js/app.min.js')
, promiseRev(config.clientBuildDir + '/css/main.css')
, promiseFileData(fs.readFile, indexPath)
];
Promise.all(promises).then((results) => {
try {
const transforms = [
{old: 'js/app.min.js', new: 'app.min-' + results[0] + '.js'}
, {old: 'css/main.css', new: 'main-' + results[1] + '.css'}
];
const html = transformText(results[2], transforms);
Promise.all(
R.append(
promiseFileWrite(indexPath, html)
, R.map(promiseMoveFile, transforms)
)
).then(() => done(), done);
}
catch(e) {
done(e);
}
}, done);
}
catch(error) {
done(error);
}
});
gulp.task('static:watch', () => {
return gulp.watch('./client/index.html', ['static:reload'])
});
const applyCssPlugin = (bundler) => {
bundler.plugin(cssModulesify, {
rootDir: __dirname
, output: config.clientBuildDir + '/css/main.css'
});
};
const runBundle = (bundler) => {
applyCssPlugin(bundler);
return bundler
.transform(babelify)
.bundle()
.on('log', gutil.log)
.on('data', () => {})
.on('error', (e) => gutil.log(gutil.colors.red('Error bundling'), e))
.on('end', (e) => {
// start is deprecated and will be removed in a future release,
// but no alternatives are given other than pulling in deps that
// ultimately use start.
gulp.start('static:index:rev');
console.log('finished bundling');
})
.pipe(source('app.min.js'))
.pipe(gulp.dest(config.clientBuildDir + '/js'))
;
};
const buildJs = (watching) => {
gutil.log('building... (watching=' + watching + ')');
const browserifyOpts = {
entries: ['./client/app/app.js']
, extensions: ['.jsx', '.js']
, debug: true
// TODO: Add watch: true and keepAlive: true
};
const watchifyOpts = R.merge(watchify.args, browserifyOpts);
var bundler;
if(watching) {
bundler = watchify(browserify(watchifyOpts));
gulp.watch('./client/styles/**/*.scss', () => {
gutil.log('styles were changed, updating...');
runStyles()
.on('end', () => {
gutil.log('done updating styles, rebuilding css-modules');
});
});
}
else {
bundler = browserify(watchifyOpts);
}
bundler.on('log', gutil.log);
bundler.on('update', (event) => {
gutil.log('updating... (watching=' + watching + ')', event);
runBundle(bundler)
.on('end', browserSync.reload);
gutil.log('update complete');
});
if(watching) {
// actually do the build
buildJs(false);
}
return runBundle(bundler);
};
gulp.task('build-once', ['styles'], R.partial(buildJs, false));
gulp.task('build-and-watch', ['styles'], R.partial(buildJs, true));
gulp.task('build', ['build-once', 'static:copy'], () => {
// does this need a callback?
gutil.log('Done with build');
});
gulp.task('browser-sync', [], () => {
browserSync.init({
server: {
baseDir: './dist'
}
, port: 10001
, open: false
});
gutil.log('initialized browser-sync');
});
gulp.task('host:main', ['watch-server-test'], () => {
if(!fs.existsSync('./server/app.js')) {
gutil.log('No server script found. Refusing to host server.');
return;
}
nodemon({
script: './server/app.js'
, ext: 'html js'
, env: {'NODE_ENV': 'development'}
, stdout: false
, stderr: false
//, nodeArgs: ['--debug']
, nodeArgs: ['--harmony']
, watch: 'server/**/!(*.spec).js'
});
nodemon.on('restart', (files) => {
gutil.log('[server] App restarted due to', gutil.colors.cyan(files));
}).on('stdout', (raw) => {
const message = raw.toString('utf8');
gutil.log('[server]', gutil.colors.green(message));
if(message.indexOf('[server] Restart complete.') != -1) {
//browserSync.reload();
}
}).on('stderr', (err) => {
const message = err.toString('utf8');
// For some reason debugger attachment gets logged on 'stderr', so we catch it here...
//if(message.indexOf('debugger listening on port' == 0)) {
// gutil.log('[server]', gutil.colors.green(message));
//}
//else {
handleError('[server]')(message);
//}
})
;
});
@LoganBarnett
Copy link
Author

Added file rev to defeat browser cache.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment