Gulp 4 error: "Did you forget to signal async completion?" - node.js

I am working on a small project that needs .sass files compiled into .css files. I have used Gulp a while ago and loved it, but my old gulpfile.js does not work anymore, because Gulp has changed since version 4.
I have made a new gulpfile.js:
var gulp = require('gulp'),
sass = require('gulp-sass'),
rename = require('gulp-rename');
var paths = {
styles: {
src: 'src/scss/*.scss',
dest: 'build/css'
}
};
function styles() {
return gulp
.src(paths.styles.src, {
sourcemaps: true
})
.pipe(sass())
.pipe(rename({
basename: 'main',
suffix: '.min'
}))
.pipe(gulp.dest(paths.styles.dest));
}
function watch() {
gulp
.watch(paths.styles.src, styles);
}
var syncConfig = {
server: {
baseDir : './',
index : 'index.html'
},
port : 3000,
open : false
};
// browser-sync
function server() {
init(syncConfig);
}
var build = gulp.parallel(styles, watch, server);
gulp
.task(build);
gulp
.task('default', build);
I have a "Did you forget to signal async completion?" error returned by the console.
Where is my mistake?

There ware two things missing: the browsersync variable browsersync = require('browser-sync').create() and the callback for the server function:
function server(done) {
if (browsersync) browsersync.init(syncConfig);
done();
}
It compiles SASS to CSS, still there is this problem: the page does not reload automatically when changes are made in the main.scss.
Here is the entire code:
var gulp = require('gulp'),
browsersync = require('browser-sync').create(),
sass = require('gulp-sass'),
rename = require('gulp-rename');
var paths = {
styles: {
src: 'src/scss/*.scss',
dest: 'build/css'
}
};
function styles() {
return gulp
.src(paths.styles.src, {
sourcemaps: true
})
.pipe(sass())
.pipe(rename({
basename: 'main',
suffix: '.min'
}))
.pipe(gulp.dest(paths.styles.dest));
}
function watch() {
gulp
.watch(paths.styles.src, styles);
}
var syncConfig = {
server: {
baseDir : './',
index : 'index.html'
},
port : 3000,
open : false
};
// browser-sync
function server(done) {
if (browsersync) browsersync.init(syncConfig);
done();
}
var build = gulp.parallel(styles, watch, server);
gulp
.task(build);
gulp
.task('default', build);

Related

Gulp project running locally but unable to build

I am trying building a website with a clone from https://github.com/cssninjaStudio/krypton.
I can run the project locally with yarn run dev command working properly, but when i try to build the app to host in a VPS with yarn build or yarn run prod giving an error
Task never defined: prod
Here is my gulp.js
const del = require('del');
const options = require("./config");
const browserSync = require('browser-sync').create();
const sass = require('gulp-sass');
const bourbon = require('node-bourbon').includePaths;
const postcss = require('gulp-postcss');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const imagemin = require('gulp-imagemin');
const cleanCSS = require('gulp-clean-css');
const purgecss = require('gulp-purgecss');
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
const panini = require('panini');
const browserify = require("browserify");
const babelify = require("babelify");
const source = require("vinyl-source-stream");
const nodepath = 'node_modules/';
sass.compiler = require('sass');
//Note : Webp still not supported in major browsers including forefox
//const webp = require('gulp-webp'); //For converting images to WebP format
//const replace = require('gulp-replace'); //For Replacing img formats to webp in html
const logSymbols = require('log-symbols'); //For Symbolic Console logs :) :P
//Load Previews on Browser on dev
function livePreview(done) {
browserSync.init({
server: {
baseDir: options.paths.dist.base
},
port: options.config.port || 5000
});
done();
}
//Copy latest installed Bulma
function setupBulma() {
console.log("\n\t" + logSymbols.info, "Installing Bulma Files..\n");
return src([nodepath + 'bulma/*.sass', nodepath + 'bulma/**/*.sass'])
.pipe(dest('src/sass/'));
}
//Compile Sass code
function compileSASS() {
console.log("\n\t" + logSymbols.info, "Compiling Bulma Sass..\n");
return src(['src/sass/bulma.sass'])
.pipe(sass({
outputStyle: 'compressed',
sourceComments: 'map',
sourceMap: 'sass',
includePaths: bourbon
}).on('error', sass.logError))
.pipe(autoprefixer('last 2 versions'))
.pipe(dest('dist/assets/css'))
.pipe(browserSync.stream());
}
//Compile Scss code
function compileSCSS() {
console.log("\n\t" + logSymbols.info, "Compiling App SCSS..\n");
return src(['src/scss/main.scss'])
.pipe(sass({
outputStyle: 'compressed',
sourceComments: 'map',
sourceMap: 'scss',
includePaths: bourbon
}).on('error', sass.logError))
.pipe(autoprefixer('last 2 versions'))
.pipe(dest('dist/css'))
.pipe(browserSync.stream());
}
//Compile HTML partials with Panini
function compileHTML() {
console.log("\n\t" + logSymbols.info, "Compiling HTML..\n");
panini.refresh();
return src('src/pages/**/*.html')
.pipe(panini({
root: 'src/pages/',
layouts: 'src/layouts/',
partials: 'src/partials/',
helpers: 'src/helpers/',
data: 'src/data/'
}))
.pipe(dest('dist'))
.pipe(browserSync.stream());
}
//Concat CSS Plugins
function concatCssPlugins() {
console.log("\n\t" + logSymbols.info, "Compiling Plugin styles..\n");
return src([
nodepath + 'simplebar/dist/simplebar.min.css',
nodepath + 'plyr/dist/plyr.css',
nodepath + 'codemirror/lib/codemirror.css',
nodepath + 'codemirror/theme/shadowfox.css',
'src/vendor/css/*',
])
.pipe(sourcemaps.init())
.pipe(concat('app.css'))
.pipe(sourcemaps.write('./'))
.pipe(dest('dist/css'))
.pipe(browserSync.stream());
}
//Reset Panini Cache
function resetPages(done) {
console.log("\n\t" + logSymbols.info, "Clearing Panini Cache..\n");
panini.refresh();
done();
}
//Triggers Browser reload
function previewReload(done) {
console.log("\n\t" + logSymbols.info, "Reloading Browser Preview.\n");
browserSync.reload();
done();
}
//Development Tasks
function devHTML() {
return src(`${options.paths.src.base}/**/*.html`).pipe(dest(options.paths.dist.base));
}
//Optimize images
function devImages() {
return src(`${options.paths.src.img}/**/*`).pipe(dest(options.paths.dist.img));
}
// Let's write our task in a function to keep things clean
function javascriptBuild() {
// Start by calling browserify with our entry pointing to our main javascript file
return (
browserify({
entries: [`${options.paths.src.js}/main.js`],
// Pass babelify as a transform and set its preset to #babel/preset-env
transform: [babelify.configure({ presets: ["#babel/preset-env"] })]
})
// Bundle it all up!
.bundle()
// Source the bundle
.pipe(source("bundle.js"))
// Then write the resulting files to a folder
.pipe(dest(`dist/js`))
);
}
function copyFonts() {
console.log("\n\t" + logSymbols.info, "Copying fonts to dist folder.\n");
return src([
'src/fonts/*',
])
.pipe(dest('dist/fonts'))
.pipe(browserSync.stream());
}
//Copy data files
function copyData() {
console.log("\n\t" + logSymbols.info, "Copying data files..\n");
return src([
'src/data/**/*',
])
.pipe(dest('dist/data'))
.pipe(browserSync.stream());
}
function watchFiles() {
//watch('src/**/*.html', compileHTML);
watch(`${options.paths.src.base}/**/*.html`, series(compileHTML, previewReload));
watch(['src/scss/**/*', 'src/scss/*'], compileSCSS);
watch(`${options.paths.src.js}/**/*.js`, series(javascriptBuild, previewReload));
watch(`${options.paths.src.img}/**/*`, series(devImages, previewReload));
console.log("\n\t" + logSymbols.info, "Watching for Changes..\n");
}
function devClean() {
console.log("\n\t" + logSymbols.info, "Cleaning dist folder for fresh start.\n");
return del([options.paths.dist.base]);
}
exports.setup = series(setupBulma);
exports.default = series(
devClean, // Clean Dist Folder
resetPages,
parallel(copyFonts, concatCssPlugins, compileSCSS, javascriptBuild, devImages, compileHTML),
livePreview, // Live Preview Build
watchFiles // Watch for Live Changes
);
Need some help to build this website and host it in VPS
Many Thanks in Advance
The prod task is not define within the Gulp file. The dev task is, because it is calling the default gulp task (gulp with no arg is calling the default which is found at the end of the gulp file
exports.default = series(
devClean, // Clean Dist Folder
resetPages,
parallel(copyFonts, concatCssPlugins, compileSCSS, javascriptBuild, devImages, compileHTML),
livePreview, // Live Preview Build
watchFiles // Watch for Live Changes
);
Take a look at your package.json file, this is were the script name are define (such as dev and prod.)
"scripts": {
"dev": "gulp",
"build": "gulp prod",
"prod": "gulp prod",
"preinstall": "npx npm-force-resolutions"
},
So you should create a prod method in your gulp.js and should only call usefull method for prod env (remove livePreview and watch, you are most likely only build and deploy.)
I prefer to task definition like this,
gulp.task("prod", function (callback) {
config.runCleanBuilds = true;
return runSequence(
"taskA",
"taskB",
"taskC",
callback);
});
but you could do it the same way they do in their gulp file I guess
exports.prod = series(
devClean, // Clean Dist Folder
resetPages,
parallel(copyFonts, concatCssPlugins, compileSCSS, javascriptBuild, devImages, compileHTML)
);

After upgrade to Gulp 4 default task is not detecting default changes for JS & Scss

I upgraded the gulp to 4.0.2 from Gulp version 3. it will not detect changes when the tracked JSa and SCSS file is changed.
Gulp version I am using :-
CLI version: 2.3.0
Local version: 4.0.2
gulpfile.js
'use strict';
var gulp = require('gulp'),
sass = require('gulp-sass'),
del = require('del'),
jshint = require('gulp-jshint'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify'),
strip = require('gulp-strip-comments'),
livereload = require('gulp-livereload'),
http = require('http'),
st = require('st'),
sourcemaps = require('gulp-sourcemaps'),
ngAnnotate = require('gulp-ng-annotate'),
babel = require('gulp-babel'),
uglifycss = require('gulp-uglifycss'),
browserSync = require('browser-sync').create();
//Rerun the task when a file changes
var watch_hintJs = ['./global/util/*.js', './global/util/**/*.js', './modules/**/*Service.js', './modules/**/*Directive.js', './modules/**/*Controller.js', './modules/**/*Constant.js'];
var watch_hintscss = ['./global/scss/*.scss', './modules/**/*.scss'];
// This method is used to delete the files
gulp.task('clean', ()=> {
return del(['./assets/css']);
});
var globalCSS = ['./assets/libs/css/**','./assets/libs/css/*.css'];
gulp.task('css', ()=> {
return gulp.src(globalCSS)
.pipe(concat('myapp-main-libs.css'))
.pipe(uglifycss({
"uglyComments": true
}))
.pipe(gulp.dest('./assets/css/'));
});
/* SASS TO CSS CONVERSION*/
gulp.task('sass', ()=> {
return gulp.src(['./global/scss/*.scss', './global/scss/lib/*.scss', './modules/**/*.scss'])
.pipe(sass().on('error', sass.logError))
.pipe(sass())
.pipe(concat('myapp-main.css'))
//.pipe(strip())
.pipe(uglifycss({
"uglyComments": true
}))
.pipe(gulp.dest('./assets/css/'));
});
//This method is converting all JS files to Single file//
var jsFiles = ['./global/util/*.js', './global/util/lib/*.js', './global/util/components/*.js',
'./modules/**/*Service.js', './modules/**/*Directive.js', './modules/**/*Controller.js', './modules/**/*Constant.js'],
jsDest = './assets/js/',
jsLibs = [
'assets/libs/js/tether.min.js',
'assets/libs/js/jquery.min.js',
'assets/libs/js/jquery-ui-min.js',
'assets/libs/js/bootstrap.min.js',
'assets/libs/js/angular.min.js',
'assets/libs/js/angular-ui-router.min.js',
'assets/libs/js/ui-grid-min.js',
'assets/libs/js/html2canvas.js',
'assets/libs/js/ui-bootstrap-tpls-2.5.0.min.js',
'assets/libs/js/accordian.js',
'assets/libs/js/angularResizable.js',
'assets/libs/js/angular-animate.min.js',
'assets/libs/js/ngToast.js',
'assets/libs/js/angular-sanitize.js',
'assets/libs/js/pubsub.js',
'assets/libs/js/angular-environment.js',
'assets/libs/js/deferred-with-update.js',
'assets/libs/js/multiselect.js',
'assets/libs/js/angular-chart.min.js',
'assets/libs/js/common.js',
'assets/libs/js/bootstrap-colorpicker-module.min.js',
'assets/libs/js/dom-to-image.js',
'assets/libs/js/alasql.min.js',
'assets/libs/js/xlsx.core.min.js',
'node_modules/babel-polyfill/dist/polyfill.min.js',
'assets/libs/js/jquery.csv.js',
'assets/libs/js/z-worker.js',
'assets/libs/js/zip.js'
];
gulp.task('libs', ()=> {
return gulp.src(jsLibs)
.pipe(strip())
.pipe(concat('myapp-lib-scripts.js'))
.pipe(gulp.dest(jsDest));
});
var minify = require('gulp-minify');
gulp.task('scripts', ()=> {
return gulp.src(jsFiles)
.pipe(jshint())
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['es2015', 'stage-3'],
"plugins": ["transform-async-to-generator"]
}))
.pipe(concat('myapp-scripts.js'))
.pipe(uglify({
mangle: false
}))
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest(jsDest))
.pipe(livereload());
});
/*jshint, watch, browserify*/
// configure the jshint task
gulp.task('jshint', ()=> {
return gulp.src(watch_hintJs)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('browser-sync', gulp.series('sass', ()=> {
browserSync.init({
server: {
injectChanges: true,
baseDir: "./"
},
browser: ["chrome.exe"]
});
}));
gulp.task('js-watch', gulp.series('scripts', () =>{
console.log('you changed the JS');
return browserSync.reload();
}));
gulp.task('css-watch', gulp.series('sass', ()=> {
console.log('you changed the css');
return browserSync.reload();
}));
gulp.task('watch', gulp.series('browser-sync', ()=> {
console.log('you reach watch');
gulp.watch(watch_hintJs, ['js-watch']);
gulp.watch(watch_hintscss, ['css-watch']);
gulp.watch(watch_hintJs, browserSync.reload());
return livereload.listen();
}));
gulp.task('server', (done)=> {
return http.createServer(
st({
path: __dirname + '/',
index: 'index.html',
cache: false
})
).listen(8080, done);
});
var revts = require('gulp-rev-timestamp');
gulp.task('rev-timestamp', ()=> {
return gulp.src("./index.html")
.pipe(revts())
.pipe(gulp.dest('.'));
});
gulp.task('default', gulp.series('clean', 'css', 'sass', 'libs', 'scripts', 'rev-timestamp', 'watch'));
gulp.task('prod', gulp.series('clean', 'css', 'sass', 'libs', 'scripts', 'jshint', 'rev-timestamp'));
Note: Style task is working correctly and moving all .scss files from source to destination.
I really appreciate any help since I am running out of ideas
Finally, I found the solution as below:-
gulp.task('watch', ()=> {
console.log('you reach watch');
gulp.watch(watch_hintJs).on('change',gulp.parallel('js-watch'));
gulp.watch(watch_hintscss).on('change',gulp.parallel('css-watch'));
return livereload.listen();
});

Getting error event.js:174 throw er; everytime I save any scss file

Here's a Screen Shot of the error event.js:174
I did a lot of research and googled a lot. I tried uninstalling and re-installing everything. Made new files again but still no luck. I tried on my laptop and it works smoothly without any errors. I am using Windows 7 64 bit desktop.
Am I doing anything wrong in Gulp? Here's the gulp code:
const gulp = require('gulp');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const cleanCSS = require('gulp-clean-css');
const browserSync = require('browser-sync').create();
const concat = require('gulp-concat');
const minify = require('gulp-minify');
const rename = require('gulp-rename');
const imagemin = require('gulp-imagemin');
const sourcemaps = require('gulp-sourcemaps');
const postcss = require('gulp-postcss');
//const webp = require('gulp-webp');
const log = require('fancy-log');
const g = require("gulp-load-plugins")();
const purgecss = require('gulp-purgecss');
const critical = require('critical').stream;
gulp.task('purgecss', () => {
return gulp.src('./dist/css/*.css')
.pipe(purgecss({
content: ["./dist/*.html"]
}))
.pipe(gulp.dest('./dist/css/purged'))
})
// Extract Media Queries & Make Seperate CSS Files
gulp.task("extractmedia", function() {
gulp.src("./dist/css/*.css")
.pipe(g.extractMediaQueries())
.pipe(gulp.dest("./dist/css/"));
});
// CSS Tasks
gulp.task('css-compile', function() {
gulp.src('scss/**/*.scss')
.pipe(sass({outputStyle: 'nested'}).on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 10 versions'],
cascade: false
}))
.pipe(gulp.dest('./dist/css/'));
});
gulp.task('minify-css', function() {
gulp.src(['./dist/css/*.css', '!dist/css/*.min.css'])
.pipe(cleanCSS())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('./dist/css'))
});
// JavaScript Tasks
gulp.task('js-build', function() {
const plugins = getJSModules();
return gulp.src(plugins.modules)
.pipe(concat('modules.js'))
.pipe(gulp.dest('./dist/js/'));
});
gulp.task('js-minify', function() {
gulp.src(['./dist/js/*.js', '!dist/js/*.min.js'])
.pipe(minify({
ext:{
src:'.js',
min:'.min.js'
},
noSource: true,
}))
.pipe(gulp.dest('./dist/js'));
});
// Image Compression
gulp.task('img-compression', function() {
gulp.src('./img/*')
.pipe(imagemin([
imagemin.gifsicle({interlaced: true}),
imagemin.jpegtran({progressive: true}),
imagemin.optipng({optimizationLevel: 5}),
imagemin.svgo({
plugins: [
{removeViewBox: true},
{cleanupIDs: false}
]
})
]))
//.pipe(webp())
.pipe(gulp.dest('./dist/img'));
});
// Generate & Inline Critical-path CSS
gulp.task('critical', function () {
return gulp.src('./dist/*.html')
.pipe(critical({base: './dist/', inline: true, css: ['./dist/css/app.min.css']}))
.on('error', function(err) { log.error(err.message); })
.pipe(gulp.dest('./dist/'));
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return gulp.src("dist/scss/*.scss")
.pipe(sass())
.pipe(gulp.dest("dist/css"))
.pipe(browserSync.stream({match: '**/*.css'}))
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(postcss([ autoprefixer({ browsers: [
'Chrome >= 35',
'Firefox >= 38',
'Edge >= 12',
'Explorer >= 10',
'iOS >= 8',
'Safari >= 8',
'Android 2.3',
'Android >= 4',
'Opera >= 12']})]))
.pipe(sourcemaps.write())
.pipe(gulp.dest('css/'))
.pipe(cleanCSS())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('css/'))
});
// Static Server + watching scss/html files
gulp.task('serve', ['sass'], function() {
browserSync.init({
injectChanges: true,
server: "./dist"
});
gulp.watch("dist/scss/*.scss", ['sass']);
gulp.watch("dist/*.html").on('change', browserSync.reload);
});
gulp.task('default', ['serve'], function() {
gulp.watch("scss/**/*.scss", ['css-compile']);
gulp.watch(["dist/css/*.css", "!dist/css/*.min.css"], ['minify-css']);
gulp.watch("js/**/*.js", ['js-build']);
gulp.watch(["dist/js/*.js", "!dist/js/*.min.js"], ['js-minify']);
gulp.watch("**/*", {cwd: './img/'}, ['img-compression']);
});
function getJSModules() {
delete require.cache[require.resolve('./js/modules.js')];
return require('./js/modules');
}
Please Help I am Stuck. As every time I save scss file I get this error all of a sudden which sucks hell lot of time for me to develop further. Sometimes it works fine but after 3-4 save file it crashes.
Found the Solution: It was all about the Folder Permissions. Hope this helps someone.

Gulp Images Failing in Ubuntu 16

I'm running my own Ubuntu 16.04.1 droplet and have just installed 'nodejs', npm, and bower globally. Then installed npm and bower on the Sage theme I've been working with. I'm able to gulp almost everything but once I get to images, I'm thrown with an error I've been having trouble diagnosing. Any help is always much appreciated!
root#myserver-ubuntu:/var/www/html/mydomain.com/public_html/bedrock/web/app/themes/mytheme# gulp images
[00:46:45] Using gulpfile /var/www/html/mydomain.com/public_html/bedrock/web/app/themes/mytheme/gulpfile.js
[00:46:45] Starting 'images'...
events.js:141
throw er; // Unhandled 'error' event
^
Error: Command failed: /var/www/html/mydomain.com/public_html/bedrock/web/app/themes/mytheme/node_modules/optipng-bin/vendor/optipng -strip all -clobber -force -fix -o 2 -out /tmp/2fd7e3c1-977c-4ac4-9886-a84ecd44e9e8 /tmp/49ebf02e-f383-46e2-bc40-d6b03b441380
/var/www/html/mydomain.com/public_html/bedrock/web/app/themes/mytheme/node_modules/optipng-bin/vendor/optipng: 1: /var/www/html/mydomain.com/public_html/bedrock/web/app/themes/mytheme/node_modules/optipng-bin/vendor/optipng: Syntax error: "(" unexpected
at ChildProcess.exithandler (child_process.js:213:12)
at emitTwo (events.js:87:13)
at ChildProcess.emit (events.js:172:7)
at maybeClose (internal/child_process.js:821:16)
at Socket.<anonymous> (internal/child_process.js:319:11)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at Pipe._onclose (net.js:469:12)
This is the gulpfile.js -
// ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var less = require('gulp-less');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(function() {
return gulpif('*.less', less());
})
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12'
]
})
.pipe(cssNano, {
safe: true
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/styles/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/scripts/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
});
I will update this for anybody that may fall here in the future.
I couldn't locate the exact reason why gulp failed, my guess is that it's a spacing/tab bug. I deleted node_modules from the sage theme and reran npm install, and the error corrected itself.

requirejs optimization with gulp

I am using requirejs and gulp to build angular app. I am using amd-optimize and gulp-requirejs-optimize to add all js files into single file. Here is my main.js file:
require.config(
{
paths: {
app : 'app',
angular : '../bower_components/angular/angular',
jquery : '../bower_components/jquery/dist/jquery',
angularResource : '../bower_components/angular-resource/angular-resource',
angularRoute : '../bower_components/angular-route/angular-route',
publicModule : 'public_module',
route : 'route'
},
shim: {
'app': {
deps: ['angular']
},
'angularRoute': ['angular'],
angular : {exports : 'angular'}
}
}
);
And gulpfile.js
var gulp = require('gulp');
var rjs = require('gulp-requirejs');
var connect = require('gulp-connect');
var requirejsOptimize = require('gulp-requirejs-optimize');
var amdOptimize = require('amd-optimize');
var concat = require('gulp-concat');
// using amd-optimize.
gulp.task('bundle', function () {
return gulp.src('app/**/*.js')
.pipe(amdOptimize('main'))
.pipe(concat('main-bundle.js'))
.pipe(gulp.dest('dist'));
});
// using gulp-requirejs-optimize.
gulp.task('scripts', function () {
return gulp.src('app/main.js')
.pipe(requirejsOptimize())
.pipe(gulp.dest('dist'));
});
When I run gulp bundle or gulp scripts, it shows me same content of main.js file in output file(not showing all js template in one output file).
The output file is:
require.config({
paths: {
angular: '../bower_components/angular/angular',
jquery: '../bower_components/jquery/dist/jquery',
angularResource: '../bower_components/angular-resource/angular-resource',
angularRoute: '../bower_components/angular-route/angular-route',
publicModule: 'public_module',
route: 'route'
},
shim: {
'app': { deps: ['angular'] },
'angularRoute': ['angular'],
angular: { exports: 'angular' }
}
});
define('main', [], function () {
return;
});
How can I configure gulp to put every js template into one js file?
check the docs for all the options for amdoptimize. For example you can point to your config file or add paths.
I always have trouble getting all the paths to line up, so make sure to check them diligently.
here is how you can start to put the options in:
gulp.task('requirejsBuild', function() {
gulp.src('app/**/*.js',{ base: 'app' })
.pipe(amdOptimize("app",{
baseUrl: config.app,
configFile: 'app/app-config.js',
findNestedDependencies: true,
}))
.pipe(concat('app.js'))
.pipe(gulp.dest('dist'))
});
You are not requiring any files - you just define an empty module named main.
You need to kick off you app by requiring a module, eg.
require(['app'], function (App) {
new App().init();
});

Resources