Skip to content

Instantly share code, notes, and snippets.

@bigglesrocks
Last active October 5, 2016 19:19
Show Gist options
  • Save bigglesrocks/e3df70d86ed72ae7b21fdfa51ecece75 to your computer and use it in GitHub Desktop.
Save bigglesrocks/e3df70d86ed72ae7b21fdfa51ecece75 to your computer and use it in GitHub Desktop.
Deluxe Gulpfile
var autoprefixer = require('gulp-autoprefixer'),
bower = require('bower'),
cache = require('gulp-cache'),
combineMq = require('gulp-combine-mq'),
concat = require('gulp-concat'),
connect = require('gulp-connect'),
fs = require('fs'),
gulp = require('gulp-param')(require('gulp'), process.argv),
gulpBower = require('gulp-bower'),
gutil = require('gulp-util'),
hljs = require('highlight'),
iconfont = require('gulp-iconfont'),
imagemin = require('gulp-imagemin'),
livereload = require('gulp-livereload'),
markdown = require('gulp-markdown'),
marked = require('marked'),
mkpath = require('mkpath'),
minifycss = require('gulp-minify-css'),
notify = require("gulp-notify"),
nunjucksRender = require('gulp-nunjucks-render'),
order = require("gulp-order"),
p = require('./package.json'),
path = require('path'),
plumber = require('gulp-plumber'),
rename = require("gulp-rename"),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
svgmin = require('gulp-svgmin'),
svgSprite = require('gulp-svg-sprite'),
uglify = require('gulp-uglify'),
watch = require('gulp-watch');
var icons = {
success: path.join(__dirname, "/utilities/", "icon-success.png"),
error: path.join(__dirname, "/utilities/", "icon-error.png"),
app: path.join(__dirname, "/node_module/gulp-notify/examples/", "gulp.png")
},
iconFontOptions = {
fontName: 'icons',
appendUnicode: true
},
config = require('./config.js'),
utilities = require("./utilities/utilities.js");
// HTML templating configuration
// ========================================
// Confifure Nunjucks templating engine
var njEnv = nunjucksRender.nunjucks.configure(['src'], { watch: true, noCache: true });
// Add filter for converting strings to valid css class names
njEnv.addFilter("klassify", utilities.njFilters.klassify);
njEnv.addFilter("parseMonth", utilities.njFilters.parseMonth);
// Error handling
// ========================================
// Setup an error handler to format errors, output to terminal, and create a notification
var errorHandler = function(error) {
notify.onError({
title: 'Error: <%= error.message %>',
subtitle: "On line <%= error.lineNumber %> of <%= error.fileName.substr(error.fileName.lastIndexOf('/') + 1) %>",
message: "<%= error.fileName %>",
sound: 'Basso',
icon: icons.error,
appIcon: icons.app,
open: '<%= error.fileName %>',
emitError: true
})(error);
gutil.log(gutil.colors.cyan(error.plugin)+': ['+gutil.colors.red.bold("ERROR")+'] '+gutil.colors.red(error.name));
gutil.log(gutil.colors.blue('Line '+error.lineNumber+': '+error.fileName));
if(error.message) {
gutil.log(gutil.colors.red.bold(error.message));
} else {
guitl.log("No Error Message!");
}
if(error.stack != undefined) {
gutil.log(gutil.colors.yellow('STACK TRACE -> '));
gutil.log(error.stack);
}
};
// Livereload & webserver
// ========================================
// Tiny Webserver + Livereload
gulp.task('webserver', function() {
connect.server({
root: 'dist',
livereload: true,
});
});
// Bower
// ========================================
gulp.task('bower', function() {
return gulpBower();
});
//Task for creating sass partials that runs after bower installs
gulp.task('cssToScss', function() {
return gulp.src("./bower_components/**/*.css")
.pipe(plumber(errorHandler))
.pipe(rename({
prefix: "_",
extname: ".scss"
}))
.pipe(gulp.dest(function(file) { return file.base; }))
.pipe(plumber.stop());
});
// Markup Tasks
// ========================================
// markdown
gulp.task('markdown', function() {
return gulp.src(['src/**/*.md', '!src/markup/**/*', "!src/styleref/**/*"])
.pipe(plumber(errorHandler))
.pipe(markdown({
gfm: true,
tables: true,
breaks: false,
pendantic: false,
sanitize: false,
smartLists: true,
smartypants: true,
highlight: function (code) {
return hljs.highlightAuto(code).value;
}
}))
.pipe(gulp.dest('dist/'))
.pipe(plumber.stop());
});
// Pure HTML
gulp.task('markup', function() {
return gulp.src(['src/**/*.html', '!src/markup/**/*', "!src/styleref/**/*"])
.pipe(plumber(errorHandler))
.pipe(gulp.dest('dist/'))
.pipe(plumber.stop());
});
// Nunjucks templates
gulp.task('nunjucks', ['vendorscripts'], function(env) {
if(env) { var absPath = config.domains[env]; }
else { var absPath = config.domains.dev; }
var scripts = utilities.getContents('dist/js', ".js", ["main.js", "main-min.js"], true);
return gulp.src(['src/**/*.html', '!src/markup/**/*', "!src/styleref/**/*"])
.pipe(plumber(errorHandler))
.pipe(nunjucksRender({
desc: p.description,
author: p.author,
absPath: absPath,
scripts: scripts
}))
.pipe(gulp.dest('dist/'))
.pipe(plumber.stop());
});
// Styles tasks
// ========================================
// Compile Sass, autoprefix, combine mediaqueries and minify css
gulp.task('styles', function() {
return gulp.src(['src/scss/styles.scss', 'src/styleref/styleref.scss'])
.pipe(plumber({ errorHandler: errorHandler }))
.pipe(sourcemaps.init())
.pipe(sass({ style: 'expanded'}, {sourcemap: true}))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
.pipe(combineMq())
.pipe(gulp.dest('dist/css/'))
.pipe(minifycss())
.pipe(rename(function(path) {
path.basename += "-min";
}))
.pipe(sourcemaps.write('maps', {
includeContent: false,
sourceRoot: '/dist'
}))
.pipe(gulp.dest('dist/css/'))
.pipe(plumber.stop());
});
// Javascript tasks
// ========================================
// Scripts included in the head, not concatenated
gulp.task('vendorscripts', function() {
paths = utilities.vendorScripts.paths;
paths = paths.concat(["bower_components/jquery/dist/jquery.js"]);
return gulp.src(paths)
.pipe(plumber(errorHandler))
.pipe(gulp.dest('dist/js'))
.pipe(plumber.stop());
});
// Concatenate and minify libraries, plugins, and main.js
gulp.task('scripts', function() {
// Get the files to be included
var components = utilities.getDependencies("js", config.components);
components = components.map(function(path) {
return path;
});
components.push("src/js/*.js", "src/js/**/*.js", "!src/js/vendor/*.js", "!src/js/components.js");
return gulp.src(components)
.pipe(plumber(errorHandler))
.pipe(sourcemaps.init())
.pipe(order([
"bower_components/*/*.js",
"bower_components/**/*.js",
"src/js/plugins/*.js",
"src/js/**/*.js",
"src/js/*.js"
], { base: "./" }))
.pipe(concat('main.js'))
.pipe(gulp.dest('dist/js'))
.pipe(uglify())
.pipe(rename('main-min.js'))
.pipe(sourcemaps.write('maps', {
includeContent: false,
sourceRoot: '/dist'
}))
.pipe(gulp.dest('dist/js'))
.pipe(plumber.stop());
});
// Assets
// ========================================
// Optimize and minify image assets
gulp.task('images', function() {
return gulp.src(['src/assets/img/**/*.jpg', 'src/assets/img/**/*.png', 'src/assets/img/**/*.gif'])
.pipe(plumber(errorHandler))
.pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
.pipe(gulp.dest('dist/assets/img'))
.pipe(plumber.stop());
});
//Videos
gulp.task('videos', function() {
return(gulp.src('src/assets/vid/*'))
.pipe(plumber(errorHandler))
.pipe(gulp.dest('dist/assets/vid'))
.pipe(plumber.stop());
});
//SVG Icons
// gulp.task('icons', function () {
// var config = {
// mode: {
// inline: true,
// symbol: {
// }
// }
// };
// return gulp.src('src/assets/icons/*.svg')
// .pipe(plumber(plumbOpt))
// .pipe(svgmin())
// .pipe(svgSprite(config))
// .pipe(gulp.dest('src/assets/icons'))
// .pipe(plumber.stop())
// .pipe(livereload());
// });
// Create font files from svg icons and output cssfile
gulp.task('icons', function () {
return gulp.src([utilities.basePath+'assets/icons/*.svg', 'src/assets/icons/*.svg'])
.pipe(plumber(errorHandler))
.pipe(iconfont(iconFontOptions))
.on('codepoints', function(codepoints, options) {
gulp.src('src/scss/utilities/icons.scss')
.pipe(nunjucksRender({
glyphs: codepoints,
fontName: 'icons',
className: 'icon',
fontPath: '../assets/fonts/icons/'
}))
.pipe(rename('_icons.scss'))
.pipe(gulp.dest('src/scss/'));
})
.pipe(gulp.dest('dist/assets/fonts/icons'))
.pipe(plumber.stop());
});
// Create font files from single ttf typeface
gulp.task('fonts', function() {
return gulp.src(['src/assets/fonts/**', utilities.basePath+'assets/fonts/**'])
.pipe(plumber(errorHandler))
.pipe(gulp.dest('dist/assets/fonts'))
.pipe(plumber.stop());
});
// Style Reference
// ========================================
// The styleref task generates a reference page based on you selected components and custom styles
// as well as a demo of your icon fonts
gulp.task('styleref', ['icons'], function() {
var scripts = utilities.getContents('dist/js', ".js", ["main.js", "main-min.js"], true);
return gulp.src([utilities.basePath+'assets/icons/*.svg', 'src/assets/icons/*.svg'])
.pipe(plumber(errorHandler))
.pipe(iconfont(iconFontOptions))
.on('codepoints', function(codepoints, options) {
gulp.src('src/styleref/styleref.html')
.pipe(plumber(errorHandler))
.pipe(nunjucksRender({
icons: codepoints,
desc: p.description,
author: p.author,
scripts: scripts,
absPath: config.domains.dev
}))
.pipe(rename("index.html"))
.pipe(gulp.dest('dist/styleref/'))
.pipe(plumber.stop());
})
.pipe(gulp.src('src/styleref/styleref.scss'))
.pipe(sass({ style: 'expanded'}))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
.pipe(combineMq())
.pipe(gulp.dest('dist/css'))
.pipe(plumber.stop());
});
// Generator Tasks
// ========================================
// You can use the following from the command line to generate various HTML templating files with a single command
gulp.task('layout', function(name) {
return gulp.src('utilities/templating/base_layout.html')
.pipe(rename(name+'.html'))
.pipe(gulp.dest('src/markup/layouts'));
});
gulp.task('template', function(name, layout) {
var layout = layout || 'basic',
content = "{% extends \"markup/layouts/"+layout+".html\" %}\n\n{% block content %}\n\n\n\n{% endblock %}";
fs.writeFile('src/markup/templates/'+name+".html", content);
});
gulp.task('page', function(name, template, layout, path) {
var path = path || '';
if(template) {
gulp.src('src/markup/templates/'+template+'.html')
.pipe(rename(name+".html"))
.pipe(gulp.dest('src/'+path));
} else {
var layout = layout || 'basic',
writePath = 'src',
content = "{% extends \"markup/layouts/"+layout+".html\" %}\n\n{% block content %}\n\n\n\n{% endblock %}";
if(path) { writePath += "/"+path; }
mkpath(writePath, function (err) { if (err) throw err; });
fs.writeFile(writePath+"/"+name+".html", content, function() {
gutil.log("["+gutil.colors.green("Success")+"] Created new page "+gutil.colors.cyan(name+".html")+" at "+gutil.colors.magenta(writePath));
});
}
});
// Default & Distribution
// ========================================
//Run the package task when you are ready to deploy your project
gulp.task('package', ['bower'], function() {
gutil.log('Packaging site...')
gulp.start(['nunjucks', 'styles', 'scripts', 'images', 'fonts']);
gutil.log('complete!');
});
// Default task
gulp.task('default', function() {
gulp.start('package');
});
// Watching things
// ========================================
gulp.task('watch', function() {
gulp.start('webserver');
livereload.listen();
var path = require('path');
// Watch for changes in source files
gulp.watch('src/assets/fonts/**/*', ['fonts']);
gulp.watch(['src/**/*.scss'], ['styles']);
gulp.watch(['src/js/**/*.js', '!src/js/vendor/*.js'], ['scripts']);
gulp.watch('src/js/vendor/*.js', ['markup']);
gulp.watch('src/assets/img/**/*', ['images']);
gulp.watch('src/assets/vid/**/*', ['videos']);
gulp.watch(['src/assets/icons/*.svg'], ['icons']);
gulp.watch(['src/styleref/**/*'], ['styleref']);
// Choose whether to use Nunjucks, markdown or straight HTML
// Compile Nunjucks
gulp.watch(['src/**/*.{html,md}'], ['nunjucks']);
// Compile Markdown
// gulp.watch(['src/**/*.md'], ['markdown']);
// Process HTML
// gulp.watch(['src/**/*.html'], ['markup']);
// Watch for changes in 'compiled' files
gulp.watch('dist/**', function (file) {
var relPath = 'dist\\' + path.relative('dist', file.path);
gutil.log('File changed: ' + gutil.colors.magenta(relPath));
notify({
title: "Success",
message: 'File '+relPath+' compiled successfully',
sound: 'Bottle',
icon: icons.success,
appIcon: icons.app
});
livereload.changed(file.path);
livereload();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment