I have two tasks and they are 'styles' and 'clean-styles'. A watch task watches for any changes in .less files and triggers the styles task when it finds a change. This scenario works fine.
When there is a syntax error in .less, the error is shown on cmd line by gulp-plumber and rest of execution stops which is also correct.
Upon correcting the mistake in .less, watch resumes and triggers off styles task, but styles task just completes the dependent clean-styles task and nothing proceeds further.
I also want style task to execute. Please help.
gulp.task('styles', ['clean-styles'], function () {
config.log('Less -> CSS compilation in progress... [gulp-inject, gulp-less, autoprefixer]');
var partialLessfiles = gulp.src(
[
path.join(config.paths.styles, '**/*.less'),
path.join('!' + config.paths.styles, 'index.less')
],
{read: false}
).pipe(print());
return gulp.src([path.join(config.paths.styles, 'index.less')])
.pipe(inject(partialLessfiles, injectOptions))
.pipe(plumber())
.pipe(less())
.pipe(autoprefixer())
.pipe(gulp.dest(config.paths.temp));
});
gulp.task('clean-styles', function() {
config.log('Deleting all styles from .tmp in progress...');
var files = config.paths.temp + '**/*.css';
config.clean(files);
});
config.clean = function(path) {
util.log('Deleting ' + path);
del(path);
};
gulp.task('less-watcher', function() {
config.log('Watching for any changes in .less files... [watch]');
gulp.watch([config.paths.allless], ['styles']);
});
Related
I have read online that 'run-sequence' will make sure all specified tasks will run synchronously. For some reason this is not true in my case. Am I missing something?
'convertSassToCss' is the task that does not work as intended
If I would run tasks 'cleanAllCss' and 'convertSassToCss' seperatelly, it would work.
The idea here is to first remove all css files from directory, then convert all sass files into css and place the into the cleaned dir
/// <binding BeforeBuild='clean, min:css' Clean='clean' />
"use strict";
var gulp = require("gulp"),
rimraf = require("rimraf"),
concat = require("gulp-concat"),
cssmin = require("gulp-cssmin"),
uglify = require("gulp-uglify"),
sass = require('gulp-sass'),
rename = require('gulp-rename'),
del = require('del'),
runSequence = require('run-sequence');
var paths = {
webroot: "./wwwroot/"
};
paths.cssPath = paths.webroot + "css/*.css";
paths.cssOutputPath = paths.webroot + "css";
//sass
paths.sassPath = paths.webroot + "sass/**/*.scss";
paths.sassOutputPath = paths.webroot + "./css/file";
gulp.task("cleanAllCss", function (cb) {
console.log("2 -- Removing all CSS files");
del([paths.cssOutputPath + "/*.css"], cb);
console.log("2 -- DONE - Removed all css files");
});
gulp.task("convertSassToCss", function (cb) {
console.log("3 -- Converting all SASS files into corresponding CSS");
gulp.src(paths.sassPath)
.pipe(sass())
.pipe(gulp.dest(paths.cssOutputPath));
console.log("3 -- DONE - Converting all SASS files into corresponding CSS");
});
//not working, should run in sequence
gulp.task("convertAllSassIntoCssMin", function (callback) {
console.log("1 -- Converting all SASS files into corresponding min CSS files")
runSequence('cleanAllCss', 'convertSassToCss', callback);
console.log("1 -- DONE - Converting all SASS files into corresponding min CSS files")
});
I cannot speak to run-sequence as I haven't used it before.
However, you can run tasks in sequence by using Gulp's task dependency feature, where a task will NOT run until it's dependencies have finished running.
Your new tasks signatures
cleanAllCss stays the same:
gulp.task("cleanAllCss", function (cb) { ... }
convertSassToCss changes to:
gulp.task("convertSassToCss", ['cleanAllCss'], function (cb) { ... }
convertAllSassIntoCssMin changes to:
gulp.task("convertAllSassIntoCssMin", ['convertSassToCss'], function (cb) { ... }
This ensures that convertAllSassIntoCssMin won't run until convertSassToCss has finished which in turn won't run until cleanAllCss has finished.
Refer to gulp deps:
deps
Type: Array
An array of tasks to be executed and completed before your task will
run.
gulp.task('mytask', ['array', 'of', 'task', 'names'], function() {
// Do stuff }); Note: Are your tasks running before the dependencies
are complete? Make sure your dependency tasks are correctly using the
async run hints: take in a callback or return a promise or event
stream.
You can also omit the function if you only want to run a bundle of
dependency tasks:
gulp.task('build', ['array', 'of', 'task', 'names']); Note: The tasks
will run in parallel (all at once), so don't assume that the tasks
will start/finish in order.
The problem is in the cleanAllCss task. The second parameter accepted by del is options, not the callback which you're trying to pass. The callback is never executed. Try running it manually when the removal is finished.
gulp.task("cleanAllCss", function (cb) {
console.log("2 -- Removing all CSS files");
del([paths.cssOutputPath + "/*.css"]).then(paths => {
console.log("2 -- DONE - Removed all css files");
cb();
};
});
I have a problem with the linting and live reloading in my gulp file. They take to much time to finish.
Here is my gulp file, what do I do wrong :
'use strict';
console.time("Loading plugins"); //start measuring
var gulp = require('gulp');
var connect = require('gulp-connect');
var open = require('gulp-open');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var concat = require('gulp-concat');
var babelify = require('babelify');
var sass = require('gulp-sass');
var merge = require('merge-stream'); // Merge all styles (css, sass and less) in one big bundle
var lint = require("gulp-eslint");
var config = {
port: 8001,
devBaseUrl: 'http://localhost',
paths: {
html: "./src/*.html",
externals: "./src/assets/externals/*.js",
js: "./src/**/*.js",
images: './src/assets/images/**/*',
fonts: './src/assets/css/fonts/*',
css: [
"./src/assets/css/*",
],
sass: './src/assets/css/*.scss',
dist: "./dist",
mainJS: "./src/main.js"
}
};
gulp.task('connect', ['watch'], function () {
connect.server({
root: ['dist'],
port: config.port,
base: config.devBaseUrl,
livereload: true,
fallback: './dist/index.html'
})
});
gulp.task('open', ['connect'], function () {
gulp.src('dist/index.html')
.pipe(open({uri: config.devBaseUrl + ":" + config.port + "/"}));
});
gulp.task('html', function () {
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('externals', function () {
gulp.src(config.paths.externals)
.on('error', console.error.bind(console))
.pipe(concat('external.js'))
.pipe(gulp.dest(config.paths.dist + '/externals'))
.pipe(connect.reload());
});
gulp.task('js', function () {
browserify(config.paths.mainJS)
.transform('babelify', {presets: ['es2015', 'react']})
.bundle()
.on('error', console.error.bind(console))
.pipe(source('bundle.js'))
.pipe(gulp.dest(config.paths.dist + '/scripts'))
.pipe(connect.reload());
});
gulp.task('images', function () {
gulp.src(config.paths.images)
.pipe(gulp.dest(config.paths.dist + '/images'));
});
gulp.task('styles', function () {
gulp.src(config.paths.css)
.pipe(sass())
.pipe(concat('bundle.css'))
.pipe(gulp.dest(config.paths.dist + '/css'))
.pipe(connect.reload());
});
gulp.task('fonts', function () {
gulp.src(config.paths.fonts)
.pipe(gulp.dest(config.paths.dist + '/css/fonts'));
});
gulp.task('lint', function () {
return gulp.src(config.paths.js)
.pipe(lint())
.pipe(lint.format());
});
gulp.task('watch', function () {
gulp.watch(config.paths.js, ['js', 'lint']);
gulp.watch(config.paths.css, ['styles']);
});
console.timeEnd('Loading plugins');
gulp.task('default', ['js', 'styles', 'lint', 'open', 'watch']);
The lint takes almost 20s to finish and liverolading takes 5-6s to refresh the browser after I make some changes.
Any advice?
Gulp ESLint plugin is generally very slow. I compared it to Grunt at some point (a while back) and it was about 5-10 times slower. Don't know why.
Make sure you are running latest version of ESLint and also that you don't have node_modules directory under your src folder. If you do, you can run eslint with --debug flag to make sure that ESLint is not linting files in your node_modules directory. If for some reason it does, add .eslintignore file and specify everything that you don't want to lint there.
In general, if you want instant feedback while coding, I would suggest looking into editor integrations. Pretty much every editor out there has ESLint plugin at this point. They show you errors directly in the window you are writing your code in.
We've recently come across the same issue on my team. The best workaround was to run ESLint only on the modified files, instead of all js files.
We use nodemon to watch for changed files, though gulp-watch has the same idea.
See the change event on gulp-watch.
Then you'd just run a lint function on the changed file.
You may need to resolve the relative file path.
gulp.watch(config.paths.js, ['js'])
.on('change', lintFile);
const lintFile = (file) => {
return gulp.src(file)
.pipe(eslint());
};
Is it necessary to check you code while developing?
We use another approach:
1)Do not check code while developing, because it is long, also it sometimes doesn't allow to create "fast" mock for something while debugging.
2)Check style only before commit. If something is wrong, fix style and check everything works. Also CI system could control your commits.
So, my suggestion is to remove lint from watch task.
I am using gulp to compile my ts files in to js file. when i change the ts file alone, the watch is not updating the browser. But when i change the html or css file it working fine.
I understand that, something i am missing in my watch property here. anyone help me to find the mistake here please?
here is my code :
var gulp = require('gulp'),
gulpTypescript = require('gulp-typescript')
browserSync = require('browser-sync');
var scripts = {
in : 'app/script/ts/*.*',
dest : 'app/script/js/'
}
gulp.task('typeScript', function () {
return gulp.src( scripts.in )
.pipe( gulpTypescript() )
.pipe( gulp.dest( scripts.dest ) );
});
gulp.task('browserSync', function () {
browserSync({
server: {
baseDir: 'app'
}
})
})
gulp.task('default', ['typeScript', 'browserSync'], function () {
gulp.watch([[scripts.in], ['typeScript']], browserSync.reload);
gulp.watch( ['app/*.html', 'app/styles/*.css'], browserSync.reload);
});
The possible method signatures for gulp.watch are:
gulp.watch(glob[, opts], tasks)
gulp.watch(glob[, opts, cb])
So what you're doing here makes no sense:
gulp.watch([[scripts.in], ['typeScript']], browserSync.reload);
That means you're passing 'typeScript' as part of the glob, when it is actually a task name.
Think about what you're trying to achieve:
Whenever you change a TypeScript file in scripts.in you want your typeScript task to run, so your *.ts files get compiled to scripts.dest.
Whenever a resulting *.js file in scripts.dest is changed you want the browserSync.reload callback to be executed.
So what you actually need is two different gulp.watch statements for those two steps of your TypeScript build process:
gulp.task('default', ['typeScript', 'browserSync'], function () {
gulp.watch(scripts.in, ['typeScript']); // 1st step
gulp.watch(scripts.dest + '*.*', browserSync.reload); // 2nd step
gulp.watch( ['app/*.html', 'app/styles/*.css'], browserSync.reload);
});
I'm building a workflow with Gulp for handling e-mails and I'm having some trouble.
My gulp file compiles a jade file into html, and I then want to run another task on the html file that this task outputs. I have set it up like shown in the code below.
The problem is that, even though the console says that the 'emailBuilder' task is run, it's not doing anything. But if I run 'emailBuilder' separately after 'gulp build' it does do what it should.
Image shows that emailBuilder is run last, still doesn't do what it should.
How can I make this work smoothly?
//-----------------------------------------------------
// ### REQUIREMENTS
//-------------------
var gulp = require('gulp'),
jade = require('gulp-jade'),
sass = require('gulp-sass'),
del = require('del'),
emailBuilder = require('gulp-email-builder'),
runSequence = require('gulp-run-sequence');
//-----------------------------------------------------
// ### Clean
// `gulp clean`
//-------------------
// Clean our compiled folder before we generate new content into it
gulp.task('clean', function (cb) {
del([
// here we use a globbing pattern to match everything inside the `compiled` folder, except our gitkeep file
'compiled/**/*',
], { dot: true },
cb);
});
//-----------------------------------------------------
// ### Compile SCSS
// `gulp compile-css`
//-------------------
gulp.task('compile-scss', function () {
gulp.src('./src/scss/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./compiled/css'));
});
//-----------------------------------------------------
// ### Build Jade templates
// `gulp templates`
//-------------------
gulp.task('templates', function() {
var YOUR_LOCALS = {};
gulp.src('./src/templates/*.jade')
.pipe(jade({
pretty: true,
locals: YOUR_LOCALS
}))
.pipe(gulp.dest('./compiled/templates/'));
});
//-----------------------------------------------------
// ### Inline CSS, send tests
// `gulp compile-css`
//-------------------
gulp.task('emailBuilder', function() {
return gulp.src(['./compiled/templates/*.html'])
.pipe(emailBuilder())
.pipe(gulp.dest('./compiled/templates/'));
});
//-----------------------------------------------------
// ### Build
// `gulp build` - Clean up the builds directory and do a complete build.
//-------------------
gulp.task('build', function(callback) {
runSequence(
'clean',
'compile-scss',
'templates',
'emailBuilder',
callback);
});
You need to add a return statement to your tasks. According to the gulp API docs on tasks:
Make sure your dependency tasks are correctly using the async run hints: take in a callback or return a promise or event stream.
If you don't return a promise or the event stream (or use a callback) the following tasks won't know when the previous one is done.
I suspect that in your case the emailBuilder task is run too soon.
Just wondering if someone can help me with my Gulp setup. At the moment I am using gulp-sass and gulp-scss-lint with a watch task. What I want to happen is that when an scss file is saved for the linting task to run completely and if any errors or warnings are thrown up for the scss files not to compile and for watch to continue running.
At the moment I seem to have this working with errors but not with the warnings, which still compile the stylesheets.
/// <binding ProjectOpened='serve' />
// Macmillan Volunteering Village Gulp file.
// This is used to automate the minification
// of stylesheets and javascript files. Run using either
// 'gulp', 'gulp watch' or 'gulp serve' from a command line terminal.
//
// Contents
// --------
// 1. Includes and Requirements
// 2. SASS Automation
// 3. Live Serve
// 4. Watch Tasks
// 5. Build Task
'use strict';
//
// 1. Includes and Requirements
// ----------------------------
// Set the plugin requirements
// for Gulp to function correctly.
var gulp = require('gulp'),
notify = require("gulp-notify"),
sass = require('gulp-sass'),
scssLint = require('gulp-scss-lint'),
gls = require('gulp-live-server'),
// Set the default folder structure
// variables
styleSheets = 'Stylesheets/',
styleSheetsDist = 'Content/css/',
html = 'FrontEnd/';
//
// 2. SASS Automation
// ------------------
// Includes the minification of SASS
// stylesheets. Output will be compressed.
gulp.task('sass', ['scss-lint'], function () {
gulp.src(styleSheets + 'styles.scss')
.pipe(sass({
outputStyle: 'compressed'
}))
.on("error", notify.onError(function (error) {
return error.message;
}))
.pipe(gulp.dest(styleSheetsDist))
.pipe(notify({ message: "Stylesheets Compiled", title: "Stylesheets" }))
});
// SCSS Linting. Ignores the reset file
gulp.task('scss-lint', function () {
gulp.src([styleSheets + '**/*.scss', '!' + styleSheets + '**/_reset.scss'])
.pipe(scssLint({
'endless': true
}))
.on("error", notify.onError(function (error) {
return error.message;
}))
});
//
// 3. Live Serve
// -------------
gulp.task('server', function () {
var server = gls.static('/');
server.start();
// Browser Refresh
gulp.watch([styleSheets + '**/*.scss', html + '**/*.html'], function () {
server.notify.apply(server, arguments);
});
});
// Task to start the server, followed by watch
gulp.task('serve', ['default', 'server', 'watch']);
//
// 4. Watch Tasks
// --------------
gulp.task('watch', function () {
// Stylesheets Watch
gulp.watch(styleSheets + '**/*.scss', ['scss-lint', 'sass']);
});
//
// 5. Build Task
// --------------
gulp.task('default', ['sass']);
Seems that #juanfran has answered this question on GitHub in 2015. I will just repost it here.
1) Using gulp-if you can add any condition you like.
var sass = require('gulp-sass');
var gulpif = require('gulp-if');
var scssLint = require('gulp-scss-lint')
gulp.task('lint', function() {
var condition = function(file) {
return !(file.scssLint.errors || file.scssLint.warnings);
};
return gulp.src('**/*.scss')
.pipe(scssLint())
.pipe(gulpif(condition, sass()));
});
2) Another more specific option is to use Fail reporter that will fail in case of any errors or warnings
gulp.task('scss-lint', function() {
return gulp.src('**/*.scss')
.pipe(scssLint())
.pipe(scssLint.failReporter());
});
gulp.task('sass', ['scss-lint'], function() {
return gulp.src('**/*.scss')
.pipe(scss());
});