Skip to content

Instantly share code, notes, and snippets.

@jessrodier
Created February 18, 2021 15:47
Show Gist options
  • Save jessrodier/fd01425ec5bb145a340bdb967ccb4b5a to your computer and use it in GitHub Desktop.
Save jessrodier/fd01425ec5bb145a340bdb967ccb4b5a to your computer and use it in GitHub Desktop.
Gulpfile for WordPress projects (using Gulp 4). Used to minify images, compile/autoprefix/minify SCSS (and use source maps), and uglify JS (and use source maps). Also spins up browsersync for watching files and reloading the browser - I use WAMP on my Windows 10 PC, but MAMP for Mac OS should work as well.
'use strict'; // Strict Mode
const
{ src, dest, task, watch, series, parallel } = require('gulp'),
imagemin = require('gulp-imagemin'),
sass = require('gulp-sass'),
prefix = require('gulp-autoprefixer'),
uglify = require('gulp-uglify'),
plumber = require('gulp-plumber'),
sourcemaps = require('gulp-sourcemaps'),
browserSync = require('browser-sync'),
connect = require('gulp-connect-php'),
rootdir = {
watch : '*.php'
},
styles = {
src : 'pre/styles/**/*.scss',
build : 'styles/',
watch : 'pre/styles/**/*.scss'
},
scripts = {
src : 'pre/scripts/**/*.js',
build : 'scripts/',
watch : 'pre/scripts/**/*.js'
},
assets = {
src : 'pre/assets/**/*',
build : 'assets/',
watch : 'pre/assets/**/*'
};
var reload = browserSync.reload;
///// Browser Sync & Watch - Runs and Reloads Projects
function browser_sync(done) {
connect.server({}, function (){
browserSync({ proxy: 'localhost' });
})
done();
}
function watchFiles(done) {
watch(styles.watch, buildStyles).on('change', reload);
watch(scripts.watch, buildScripts).on('change', reload);
watch(rootdir.watch).on('change', reload);
watch(assets.watch, buildAssets).on('change', reload);
done();
}
///// Compress Scripts
function buildScripts() {
return src(scripts.src)
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(dest(scripts.build))
.pipe(browserSync.stream());
}
///// Compile & Compress Styles
function buildStyles() {
return src(styles.src)
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(prefix('last 2 versions'))
.pipe(sourcemaps.write())
.pipe(dest(styles.build))
.pipe(browserSync.stream());
}
///// Compress Images
function buildAssets() {
return src(assets.src)
.pipe(imagemin())
.pipe(dest(assets.build))
.pipe(browserSync.stream());
}
///// Default: Run during development
task('default', parallel(buildScripts, buildStyles, browser_sync, watchFiles));
///// Build: Run for newly pulled project
task('build', series(buildScripts, buildStyles, buildAssets));
///// Individual Tasks
task('styles', buildStyles);
task('scripts', buildScripts);
task('assets', buildAssets);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment