gulp will not output js min file - javascript

Cant seem to find my problem here. After I run Gulp, the all-css.min.css gets outputted to _build folder but the JS will not go! am I missing something? Cant seem to find what is making this not work.
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var minifyHTML = require('gulp-minify-html');
var sourcemaps = require('gulp-sourcemaps');
var minifyCSS = require('gulp-minify-css');
var inlineCss = require('gulp-inline-css');
var rev = require("gulp-rev");
var del = require('del');
var jsBase = {
src: [
'/Scripts/Core/ko.bindinghandlers-1.0.0.js',
'/Scripts/Twitter/typeahead-0.10.2.js',
'/Scripts/LdCore/mobile-core.js',
'/Scripts/LDCore/Chat.js',
'/Scripts/unsure.js' // These have any unknown lines in them.
]
};
gulp.task('clean', function () {
del.sync(['_build/*'])
});
gulp.task('produce-css', function () {
return gulp.src(cssBase.src)
.pipe(minifyCSS({ keepBreaks: false }))
.pipe(concat('all-css.min.css'))
.pipe(gulp.dest('_build/'))
});
gulp.task('produce-minified-js', function () {
return gulp.src(jsBase.src)
//.pipe(sourcemaps.init())
//.pipe(uglify())
.pipe(concat('all.min.js'))
//.pipe(rev()) // adds random numbers to end.
//.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('_build/'));
});
gulp.task('default', ['clean'], function () {
gulp.start('produce-css', 'produce-minified-js');
});

According to Contra at this post, we shouldn't be using gulp.start.
gulp.start is undocumented on purpose because it can lead to
complicated build files and we don't want people using it
Bad:
gulp.task('default', ['clean'], function () {
gulp.start('produce-css', 'produce-minified-js');
});
Good:
gulp.task('default', ['clean','produce-css','produce-minified-js'], function () {
// Run the dependency chains asynchronously 1st, then do nothing afterwards.
});
It's totally legit to have nothing in the gulp.task, as what it's doing is running the dependency chains asynchronously & then terminating successfully.
You could also do the following:
gulp.task('default', ['clean','produce-css','produce-minified-js'], function (cb) {
// Run a callback to watch the gulp CLI output messages.
cb();
});
Since Gulp creates "Starting default" on the CLI, this would help to display "Finished default" in the CLI after everything else runs.

Related

Why is merge-stream requiring async completion signal?

I'm in the process of migrating from gulp#3.9.1 to gulp#4.0.2 and upgrading my gulp dependencies in the process. I have the following task in my gulpfile, where you can assume directories is just an array of directories I want to perform this operation on:
var gulp = require('gulp');
var ngAnnotate = require('gulp-ng-annotate'); //annotates dependencies in Angular components
var rev = require('gulp-rev'); //appends a hash to the end of file names to eliminate stale cached files
var revReplace = require('gulp-rev-replace');
var uglify = require('gulp-uglify'); // minimizes javascript files
var compressCss = require('gulp-minify-css');
var useref = require('gulp-useref'); // replaces style and script blocks in HTML files
var filter = require('gulp-filter');
var merge = require('merge-stream');
var sourcemaps = require('gulp-sourcemaps');
function minify() {
var tasks = directories.map(function (directory) {
var cssFilter = filter("**/all.min.css", {restore:true});
var jsAppFilter = filter("**/app.min.js", {restore:true});
var jsFilter = filter("**/*.js", {restore:true});
return gulp.src(dstBasePath + directory + "index.html", {allowEmpty: true})
.pipe(useref())
.pipe(cssFilter)
.pipe(compressCss({keepSpecialComments:false}))
.pipe(rev())
.pipe(cssFilter.restore)
.pipe(jsAppFilter)
.pipe(sourcemaps.init())
.pipe(ngAnnotate({add:true, single_quotes:true}))
.pipe(jsAppFilter.restore)
.pipe(jsFilter)
.pipe(uglify())
.pipe(rev())
.pipe(jsFilter.restore)
.pipe(revReplace())
.pipe(sourcemaps.write('.')) // sourcemaps need to be written to same folder for Datadog upload to work
.pipe(gulp.dest(dstBasePath + directory))
});
return merge(tasks);
}
Why would this result in the error "Did you forget to signal async completion?" from Gulp when running the task? Note that I'm using Gulp 4. I've tried passing a callback done to this task, and adding .addListener('end', done) to the final pipe, but this causes my merged stream to end prematurely (presumably when the first one ends). So perhaps one of these plugins is not signaling when it's completed, but how would you even get this to work otherwise? Thanks for any insight you can provide.
return merge(folders.map(function (folder) { // this has worked for me in the past
as has this form without merge
gulp.task('init', function (done) {
var zips = getZips(zipsPath);
var tasks = zips.map(function (zip) {
return gulp.src(zipsPath + "/" + zip)
.pipe(unzip({ keepEmpty: true }))
.pipe(gulp.dest(path.join("src", path.basename(zip, ".zip"))))
.on('end', function() { // this bit is necessary
done();
});
});
return tasks;
});
Gulp 4 requires that you signal async completion. There's some good information about it in this answer to a similar question:
Gulp error: The following tasks did not complete: Did you forget to signal async completion?
I had a similar case where I was returning a merged set of tasks, and I was able to resolve the error by making the function async and awaiting the merge. My case looked something like this:
gulp.task("build", async function () {
...
return await merge(tasks);
});
so I think you should be able to do something like
async function minify(){
...
return await merge(tasks);
}

Gulp errors trying to get uglify and default gulp to work

hi I'm having trouble setting up gulp it seems to have all changed since I last used it
I'm getting errors and can't figure out why. I'll post some pics along with my code. the first problem is that uglify doesn't complete and the second problem is that gulp default won't run the command prompt should explain my problems better than I can if you have any further questions please ask and be civil.
var gulp = require('gulp');
var sass = require('gulp-sass');
var uglifycss = require('gulp-uglifycss');
sass.compiler = require('node-sass');
gulp.task('sass', function () {
return gulp.src('./Edit/sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./Edit/css'));
});
gulp.task('css', function () {
gulp.src('./Edit/css/*.css')
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(gulp.dest('./upload/css'));
});
gulp.task('run',['sass','css']);
gulp.task('watch', function(){
gulp.watch('./Edit/sass/*.scss',['sass']);
gulp.watch('./Edit/css/*.css',['css']);
});
gulp.task('default',['watch', 'run']);
here is my output
So you've got two kinds of errors going on:
1. Task function must be specified
The way gulp runs dependent tasks has changed in v4.0.0. Instead of specifying those tasks in an array, like this:
gulp.task('run',['sass','css']);
They've introduced the gulp.series and gulp.parallel functions. A task function, and not an array, because Task function must be specified. In your case, that gives:
gulp.task('run', gulp.series('sass','css'));
2. Did you forget to signal async completion
This one you could have found, given that this question has been asked many times now. You need to add a return statement to your css task for gulp to know when it's completed and can thus move on. Your task becomes:
gulp.task('css', function () {
return gulp.src('./Edit/css/*.css')
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(gulp.dest('./upload/css'));
});
Result:
Putting it all together, you get this gulpfile:
var gulp = require('gulp');
var sass = require('gulp-sass');
var uglifycss = require('gulp-uglifycss');
sass.compiler = require('node-sass');
gulp.task('sass', function () {
return gulp.src('./Edit/sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./Edit/css'));
});
gulp.task('css', function () {
return gulp.src('./Edit/css/*.css')
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(gulp.dest('./upload/css'));
});
gulp.task('run', gulp.series('sass','css'));
gulp.task('watch', function(){
gulp.watch('./Edit/sass/*.scss',gulp.series('sass'));
gulp.watch('./Edit/css/*.css', gulp.series('css'));
});
gulp.task('default', gulp.series('watch', 'run'));
Note that you can combine your sass and css task if you'd like:
gulp.task('styles', function(){
return gulp.src('./Edit/sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(gulp.dest('./upload/css'));
});

Gulp watch doesn't "feel" new files

This is my watch.js as written by yeoman gulp-angular generator
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
function isOnlyChange(event) {
return event.type === 'changed';
}
gulp.task('watch', ['scripts:watch', 'markups', 'inject'], function () {
gulp.watch([path.join(conf.paths.src, '/*.html'), 'bower.json'], ['inject-reload']);
gulp.watch([
path.join(conf.paths.src, '/app/**/*.css'),
path.join(conf.paths.src, '/app/**/*.scss')
], function(event) {
if(isOnlyChange(event)) {
gulp.start('styles-reload');
} else {
gulp.start('inject-reload');
}
});
gulp.watch(path.join(conf.paths.src, '/app/**/*.jade'), ['markups']);
gulp.watch(path.join(conf.paths.src, '/app/**/*.html'), function(event) {
browserSync.reload(event.path);
});
});
It works fine for already created files, but for some reason gulp.watch doesn't see the new ones (in particular .jade, but maybe also other types), eg.
myApp/src/components/header/headerView.jade
The only solution for me to run task as markup is to stop and restart gulp serve. Then gulp will recognizes changes in my .jade files

Gulp watch not called from within Nodemon

So I have my Gulp file as below.
The 'watch' block seems to work absolutely fine, and do what is expected. Nodemon works in the way that it detects file changes and refreshes the server, that works too.
But I can't for the life of me get Nodemon to call the 'watch' method when a file changes.
On line 81, the .on('start' is called succesfully from nodemon, but the code inside the 'watch' method is never executed.
var gulp = require('gulp');
var gutil = require('gulp-util'); // For logging stats and warnings
var jshint = require('gulp-jshint'); // For checking JavaScript for warnings
var concat = require('gulp-concat'); // For joining together multiple files
var uglify = require('gulp-uglify'); // For minimising files
var coffee = require('gulp-coffee'); // For compiling coffee script into js
var cofLint = require('gulp-coffeelint');// For checking coffee script for errors
var less = require('gulp-less'); // For compiling Less into CSS
var cssLint = require('gulp-csslint'); // For checking the awesomeness of css
var minCss = require('gulp-minify-css');// For minifying css
var uncss = require('gulp-uncss'); // For deleting unused CSS rules
var footer = require('gulp-footer'); // For adding footer text into files
var nodemon = require('gulp-nodemon'); // For the super cool instant refreshing server
var bSync = require('browser-sync'); // Syncs the place between multiple browsers for dev
var es = require('event-stream'); // For working with streams rather than temp dirs
var sourcePath = "sources";
var destPath = "public";
var jsFileName = "all.min.js";
var cssFileName = "all.min.css";
var footerText = "";
/* JavaScript Tasks */
gulp.task('scripts', function(){
var jsSrcPath = sourcePath + '/javascript/**/*';
var jsResPath = destPath + '/javascript';
var jsFromCs = gulp.src(jsSrcPath+'.coffee')// Get all coffee script
.pipe(cofLint()) // Check CS for errors or warnings
.pipe(cofLint.reporter()) // Output the error results
.pipe(coffee()); // Convert coffee to vanilla js
var jsFromPlain = gulp.src(jsSrcPath+'.js');// get all vanilla JavaScript
return es.merge(jsFromCs, jsFromPlain) // Both js from cs and vanilla js
.pipe(jshint()) // Check js errors or warnings
.pipe(jshint.reporter('jshint-stylish')) // Print js errors or warnings
.pipe(concat(jsFileName,{newLine: ';'})) // Concatenate all files together
.pipe(uglify()) // Minify JavaScript
.pipe(footer(footerText)) // Add footer to script
.pipe(gulp.dest(jsResPath)); // Save to destination
});
/* CSS Tasks */
gulp.task('styles', function(){
var cssSrcPath = sourcePath + '/styles/**/*';
var cssResPath = destPath + '/stylesheet';
var cssFromLess = gulp.src(cssSrcPath+'.less') // Get all Less code
.pipe(less()); // Convert Less to CSS
var cssFromVanilla = gulp.src(cssSrcPath+'.css');// Get all CSS
return es.merge(cssFromLess, cssFromVanilla) // Combine both CSS
.pipe(cssLint()) // Check CSS for errors or warnings
.pipe(cssLint.reporter()) // And output the results
.pipe(concat(cssFileName)) // Concatenate all files together
.pipe(minCss({compatibility: 'ie8'})) // Minify the CSS
.pipe(gulp.dest(cssResPath)); // Save to destination
});
/* Configure files to watch for changes */
gulp.task('watch', function() {
gulp.watch(sourcePath+'/**/*.{js,coffee}', ['scripts']);
gulp.watch(sourcePath+'/**/*.{css,less}', ['styles']);
});
/* Start Nodemon */
gulp.task('demon', function () {
nodemon({
script: './bin/www',
ext: 'js coffee css less html',
env: { 'NODE_ENV': 'development'}
})
.on('start', ['watch'])//TODO: ERROR: watch is never called, even though start is called
.on('change', ['watch'])
.on('restart', function () {
console.log('restarted!');
});
});
/* Default Task */
gulp.task('default', ['demon']);
Any suggestions why this may be happening?
Is there something wrong with my Gulp file?
(and yes, I know the code is a little over-commented, I work with apprentices and they like English better than code ;)
The problem is that Nodemon and browser-sync both need to be running. This code works:
gulp.task('nodemon', function (cb) {
var called = false;
return nodemon({
script: './bin/www',
watch: ['source/**/*']
})
.on('start', function onStart() {
if (!called) { cb(); }
called = true;
})
.on('restart', function onRestart() {
setTimeout(function reload() {
bSync.reload({
stream: false
});
}, 500);
});
});
gulp.task('browser-sync', ['nodemon', 'scripts', 'styles'], function () {
bSync.init({
files: ['sources/**/*.*'],
proxy: 'http://localhost:3000',
port: 4000,
browser: ['google chrome']
});
gulp.watch(sourcePath+'/**/*.{js,coffee}', ['scripts']);
gulp.watch(sourcePath+'/**/*.{css,less}', ['styles']);
gulp.watch("sources/**/*").on('change', bSync.reload);
gulp.watch("views/**/*.jade").on('change', bSync.reload);
});
/* Default Task */
gulp.task('default', ['clean', 'browser-sync']);

gulp, tasks works individually but not in group

I have 3 task to be run sequentially : clean, mincat and then serve
var gulp = require('gulp');
var webserver = require('gulp-webserver');
var usemin = require('gulp-usemin');
var uglify = require('gulp-uglify');
var minifyHtml = require('gulp-minify-html');
var minifyCss = require('gulp-minify-css');
var rev = require('gulp-rev');
var rename = require('gulp-rename');
var del = require('del');
var sequential = require('run-sequence');
gulp.task('clean', function () {
del(['./build/*.*', './build/*']);
});
gulp.task('mincat', function () {
gulp.src('./Index.html')
.pipe(usemin({
css: [minifyCss(), 'concat'],
html: [minifyHtml({ empty: true })],
js: [uglify()],
js1: [uglify()]
}))
.pipe(gulp.dest('./build/'));
});
gulp.task('serve', function () {
gulp.src('build')
.pipe(webserver({
host: 'localhost',
port: 8080,
livereload: true,
open: true
}));
});
gulp.task('dev', function () {
sequential('clean','mincat','serve');
});
If I run the 3 tasks from command prompt one by one, it works
gulp clean
gulp mincat
gulp serve
Now I created a task to run all the 3 using single command, it doesnt work. I tried all the forms
added run-sequential plugin
gulp.task('dev', function () {
sequential('clean','mincat','serve');
});
initially run in parallel
gulp.task('dev', ['clean','mincat','serve'])
I also tried to separate the serve
gulp.task('dev', ['clean','mincat'] function () {
gulp.start('serve');
})
but non of these work, can someone point out the issue?
First, your 2 can't work, since the gulp dependencies are all runned in parallel, without specific order. The 3 can work, but it's not really recommended since it not follow the gulp guidelines.
This let us the 1. What you did is correct, but the problem you're experiencing is that gulp does not know when your tasks are finished, so it's equivalent to run everything in parallel.
To make a task synchronous, you will have to return it's stream. Since del is not a stream, you only have to use the callback. For your serve, I don't think you have to do it, since it's launched at last.
This will look like:
gulp.task('clean', function (cb) {
del(['./build/*.*', './build/*'], cb);
});
gulp.task('mincat', function () {
return gulp.src('./Index.html')
.pipe(usemin({
css: [minifyCss(), 'concat'],
html: [minifyHtml({ empty: true })],
js: [uglify()],
js1: [uglify()]
}))
.pipe(gulp.dest('./build/'));
});
I don't understand why you could have .js1 files thought, and by the way, your index.html should be lowercase :)

Categories