Gulp doesn't work when multiple tasks are run - gulp

I'm trying to grap my head around gulp. I managed to write gulpfile.js for my basic page scaffolding, but i've problems with running serveral task in order.
I'm trying to generate css/main.css file from scss files, copy it to dist/css/ and then inject my js and css files into index.html (with gulp-inject).
(function (r) {
var gulp = r('gulp');
var del = r('del');
var wiredep = r('wiredep');
var $ = r('gulp-load-plugins')();
// var runSequence = require('run-sequence');
var config = {
css_files: './css/*.css',
sass_files: './scss/*.scss',
main_sass: './scss/main.scss',
main_css: './css/main.css',
css_dir: './css/',
js_files: './js/*.js',
main_js: './js/main.js',
index: [
'./index.html',
'**/index.html',
'!node_modules/**/*.*',
'!bower_components/**/*.*',
],
dist: './dist/',
};
function clean(cb) {
del.sync([
config.css_files,
config.dist + config.css_files,
config.dist + config.js_files,
config.dist + config.index[0],
config.dist + config.index[1],
config.dist + '**/*.map',
]);
cb();
}
gulp.task('clean', function (cb) {
clean(cb);
});
gulp.task('scss', function (cb) {
gulp
.src(config.sass_files)
.pipe($.plumber())
.pipe($.sass())
.pipe(gulp.dest(config.css_dir));
cb();
});
gulp.task('js', function (cb) {
gulp
.src(config.js_files)
.pipe($.concat('main.js'))
.pipe($.sourcemaps.init())
.pipe($.uglify())
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest(config.dist + 'js/'));
cb();
});
gulp.task('css', ['scss'], function (cb) {
gulp
.src(config.css_files)
.pipe($.sourcemaps.init())
.pipe($.uglifycss())
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest(config.dist + 'css/'));
cb();
});
function wd(cb) {
wiredep({ ignorePath: '../..', src: config.main_sass, directory: './bower_components' });
wiredep({ ignorePath: '../..', src: config.index[0], directory: './bower_components' });
cb();
}
gulp.task('wd', function (cb) {
wd(cb);
});
gulp.task('inject-dev', ['wd'], function (cb) {
var src = ['!dist/**/*.*'].concat(config.index);
gulp
.src(src)
.pipe($.inject(gulp.src([config.css_files, config.js_files])))
.pipe(gulp.dest('./'));
cb();
});
gulp.task('inject-dist', ['copy-index'], function (cb) {
var src = gulp.src([config.dist + 'css/**/*.*', config.dist + 'js/**/*.*']);
var target = gulp.src(config.dist + '**/index.html');
target.pipe($.inject(src, { relative: true }))
.pipe(gulp.dest(config.dist));
cb();
});
gulp.task('watch', function (cb) {
gulp.watch(config.sass_files, ['scss']);
cb();
});
gulp.task('copy-index', function (cb) {
gulp
.src(config.index, { base: './' })
.pipe(gulp.dest(config.dist));
cb();
});
gulp.task('build-dist', ['clean', 'css', 'js', 'inject-dist']);
})(require);
ATM result of build-dist is generated js/main.js file, copied index.html and about/index.html, generated main.css in dev dir, but not in dist. Files are not injected in dist/index.html aswell.
λ szuja html-scaffold → λ git master* → tree -L 3 -I 'bower_components|node_modules'
.
├── about
│   └── index.html
├── bower.json
├── css
│   └── main.css
├── dist
│   ├── about
│   │   └── index.html
│   ├── index.html
│   └── js
│   ├── main.js
│   └── main.js.map
├── gulpfile.js
├── index.html
├── js
│   ├── main2.js
│   └── main.js
├── LICENSE
├── package.json
├── README.md
└── scss
└── main.scss
Edit:
Looks like gulp doesn't care about waiting for tasks to finish ignoring callback functions:
[16:15:47] Using gulpfile ~/workdir/html-scaffold/gulpfile.js
[16:15:47] Starting 'clean'...
[16:15:47] Finished 'clean' after 15 ms
[16:15:47] Starting 'scss'...
[16:15:47] Finished 'scss' after 75 ms
[16:15:47] Starting 'css'...
[16:15:47] Finished 'css' after 44 ms
[16:15:47] Starting 'js'...
[16:15:47] Finished 'js' after 74 ms
[16:15:47] Starting 'copy-index'...
[16:15:47] Finished 'copy-index' after 4.27 ms
[16:15:47] Starting 'inject-dist'...
[16:15:47] Finished 'inject-dist' after 13 ms
[16:15:47] Starting 'build-dist'...
[16:15:47] Finished 'build-dist' after 9.01 μs
[16:15:47] gulp-debug: 0 items
[16:15:47] gulp-debug: 0 items
[16:15:47] gulp-debug: scss/main.css
[16:15:47] gulp-debug: 1 item

Works with run-sequence and returning a promise instead of waiting for callback function. I was trying this method before, but somehow managed to pass parameters as an array, so they were running in parallel..
(function (r) {
var gulp = r('gulp');
var del = r('del');
var wiredep = r('wiredep');
var $ = r('gulp-load-plugins')();
var runSequence = require('run-sequence');
var config = {
css_files: './css/*.css',
sass_files: './scss/*.scss',
main_sass: './scss/main.scss',
main_css: './css/main.css',
css_dir: './css/',
js_files: './js/*.js',
main_js: './js/main.js',
index: [
'./index.html',
'**/index.html',
'!node_modules/**/*.*',
'!bower_components/**/*.*',
],
dist: './dist/',
};
function clean(cb) {
del.sync([
config.css_files,
config.dist + config.css_files,
config.dist + config.js_files,
config.dist + config.index[0],
config.dist + config.index[1],
config.dist + '**/*.map',
]);
cb();
}
gulp.task('clean', function (cb) {
clean(cb);
});
gulp.task('scss', function () {
return gulp
.src(config.sass_files)
.pipe($.plumber())
.pipe($.sass())
.pipe($.debug())
.pipe(gulp.dest(config.css_dir));
});
gulp.task('js', function () {
return gulp
.src(config.js_files)
.pipe($.concat('main.js'))
.pipe($.sourcemaps.init())
.pipe($.uglify())
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest(config.dist + 'js/'));
});
gulp.task('css', ['scss'], function () {
return gulp
.src(config.css_files)
.pipe($.sourcemaps.init())
.pipe($.uglifycss())
.pipe($.sourcemaps.write('./'))
.pipe($.debug())
.pipe(gulp.dest(config.dist + 'css/'));
});
function wd(cb) {
wiredep({ ignorePath: '../..', src: config.main_sass, directory: './bower_components' });
wiredep({ ignorePath: '../..', src: config.index[0], directory: './bower_components' });
cb();
}
gulp.task('wd', function (cb) {
wd(cb);
});
gulp.task('inject-dev', ['wd'], function () {
var src = ['!dist/**/*.*'].concat(config.index);
return gulp
.src(src)
.pipe($.inject(gulp.src([config.css_files, config.js_files])))
.pipe($.debug())
.pipe(gulp.dest('./'));
});
gulp.task('inject-dist', ['copy-index'], function () {
var src = gulp.src([config.dist + 'css/**/*.*', config.dist + 'js/**/*.*']);
var target = gulp.src(config.dist + '**/index.html');
return target.pipe($.inject(src, { relative: true }))
.pipe($.debug())
.pipe(gulp.dest(config.dist));
});
gulp.task('watch', function (cb) {
gulp.watch(config.sass_files, ['scss']);
cb();
});
gulp.task('copy-index', function () {
return gulp
.src(config.index, { base: './' })
.pipe(gulp.dest(config.dist));
});
gulp.task('build-dist', function (cb) {
runSequence('clean', 'js', 'css', 'inject-dist', cb);
});
})(require);

Related

Jekyll clear build folder with Gulp

I'm using a build environment with Jekyll + Gulp. So, using the gulpfile.js below, the build process generate first a dist/css folder with the compiled css inside, and then clear the entire dist folder for put the jekyll build result inside. So, i'm not able to compile the scss files inside the dist folder because every time jekyll it completely clear it.
var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var child = require('child_process');
gulp.task('jekyll', function (done) {
return child.spawn('jekyll' , ['build']).on('close', done);
});
gulp.task('jekyll-rebuild', ['jekyll'], function () {
browserSync.reload();
});
gulp.task('browser-sync', ['sass', 'jekyll'], function() {
browserSync({
server: {
baseDir: 'dist'
}
});
});
gulp.task('sass', function () {
return gulp.src('src/_sass/theme.scss')
.pipe(sass({
includePaths: ['scss'],
onError: browserSync.notify
}))
.pipe(browserSync.reload({stream:true}))
.pipe(gulp.dest('dist/css'));
});
gulp.task('watch', function () {
gulp.watch('src/_sass/*.scss', ['sass']);
gulp.watch(['src/*.html', 'src/_layouts/*.html', 'src/_includes/*'], ['jekyll-rebuild']);
});
gulp.task('default', ['browser-sync', 'watch']);
I have to avoid running jekyll task in parallel with styles and scripts so I have used a runSequence.
gulp.task('build', () => {
runSequence('jekyll', ['styles', 'scripts']);
});
gulp.task('default', ['build', 'browser-sync', 'watch']);
In your Jekyll config you need to declare which folders you want to keep:
keep_files: [ css, build ]
When clobbering the site destination, keep the selected files. Useful for files that are not generated by jekyll; e.g. files or assets that are generated by your build tool. The paths are relative to the destination.
https://jekyllrb.com/docs/configuration/

Gulp not compiling scss to correct folder

when running gulp watch it appears that its watching as the file changes. However it appears that its writting the .css file to the same folder where I am making the changes. Here is my Gulp File. I want it to put the .min.css and the .css file inside root/www/css The folder where my scss is located in /root/scss I want to be able to edit it here but have it compile and put the .css and min.css inside /root/www/css It looks looks like thats what it should be doing with these items:
.pipe(gulp.dest('./www/css/'))
.pipe(minifyCss({
But its just creating a .css file only and its in the same folder the .scss is at.
var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sh = require('shelljs');
var paths = {
sass: ['./scss/**/*.scss']
};
gulp.task('default', ['sass']);
gulp.task('sass', function(done) {
gulp.src('./scss/ionic.app.scss')
.pipe(sass({
errLogToConsole: true
}))
.pipe(gulp.dest('./www/css/'))
.pipe(minifyCss({
keepSpecialComments: 0
}))
.pipe(rename({ extname: '.min.css' }))
.pipe(gulp.dest('./www/css/'))
.on('end', done);
});
gulp.task('watch', function() {
gulp.watch(paths.sass, ['sass']);
});
gulp.task('install', ['git-check'], function() {
return bower.commands.install()
.on('log', function(data) {
gutil.log('bower', gutil.colors.cyan(data.id), data.message);
});
});
gulp.task('git-check', function(done) {
if (!sh.which('git')) {
console.log(
' ' + gutil.colors.red('Git is not installed.'),
'\n Git, the version control system, is required to download Ionic.',
'\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
'\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
);
process.exit(1);
}
done();
});
Sometimes when I add the ./ to the destinations Gulp tries to make a new directory. Taking that off usually fixes it.
gulp.task('sass', function(done) {
gulp.src('./scss/ionic.app.scss')
.pipe(sass({
errLogToConsole: true
}))
.pipe(gulp.dest('www/css/'))
.pipe(minifyCss({
keepSpecialComments: 0
}))
.pipe(rename({ extname: '.min.css' }))
.pipe(gulp.dest('www/css/'))
.on('end', done);
});

Gulp browser-sync reloads only the first time a file is saved

I start it off with
gulp sync
and get
[17:14:23] Starting 'scripts'...
[17:14:23] Finished 'scripts' after 43 ms
[17:14:23] Starting 'sync'...
[17:14:23] Finished 'sync' after 20 ms
[BS] Access URLs:
--------------------------------------
Local: http://localhost:(my port)
External: http://(my internal IP address)
--------------------------------------
UI: http://localhost:(myport+n)
UI External: http://(my internal IP address)
--------------------------------------
[BS] Serving files from: public
The browser loads up the page.
I save a file and it works. Terminal output :
[17:17:22] Starting 'scripts'...
[17:17:22] Finished 'scripts' after 17 ms
[17:17:22] Starting 'scripts-watch'...
[BS] Reloading Browsers...
I save the file again (or save a different file)
[17:18:38] Starting 'scripts'...
[17:18:38] Finished 'scripts' after 8.99 ms
Note theres no Reloading Browsers message. The browser does not reload. Stopping gulp and manually reloading the page DOES reflect the change.
My gulpfle :
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var less = require('gulp-less');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var react = require('gulp-react');
var minifyCSS = require('gulp-minify-css');
var browserSync = require('browser-sync').create();
gulp.task('less', function() {
return gulp.src('dev/less/*.less')
.pipe(less())
.pipe(minifyCSS())
.pipe(rename('styles.min.css'))
.pipe(gulp.dest('public/css'))
});
gulp.task('scripts', function() {
return gulp.src('dev/js/*.js')
.pipe(rename('scripts.min.js'))
.pipe(uglify())
.pipe(gulp.dest('public/js'));
});
gulp.task('build', function() {
return gulp.src('dev/components/**')
.pipe(concat('components.min.js'))
.pipe(react())
.pipe(uglify())
.pipe(gulp.dest('public/js'))
});
// Default Task
gulp.task('default', function() {
gulp.start('less');
gulp.start('scripts');
gulp.start('build');
});
gulp.task('scripts-watch', ['scripts'], browserSync.reload);
gulp.task('less-watch', ['less'], browserSync.reload);
gulp.task('build-watch', ['build'], browserSync.reload);
gulp.task('sync', ['scripts'], function() {
browserSync.init({
server: {
baseDir: "public",
index : "index.htm"
}
});
gulp.watch('dev/js/*.js', ['scripts-watch', browserSync.reload]);
gulp.watch('dev/less/*.less', ['less-watch', browserSync.reload]);
gulp.watch('dev/components/**', ['build-watch', browserSync.reload]);
});
Using chrome on ubuntu if that matters.

Gulp not watching files with gulp-watch plugin

I'm trying to rebuild only files that change in my gulpfile.js by using this recipe via the gulp-watch plugin. The problem is when I run my default task gulp, it doesn't watch the files at all after saving any of the files I want it to watch. What am I doing wrong here in my gulpfile.js? Thanks in advance.
/* ----------------------------------------------------- */
/* Gulpfile.js
/* ----------------------------------------------------- */
'use strict';
// Setup modules/Gulp plugins
var gulp = require('gulp'),
del = require('del'),
runSequence = require('run-sequence'),
less = require('gulp-less'),
// minifyCSS = require('gulp-minify-css'),
fileinclude = require('gulp-file-include'),
order = require('gulp-order'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
imagemin = require('gulp-imagemin'),
pngquant = require('imagemin-pngquant'),
plumber = require('gulp-plumber'),
watch = require('gulp-watch'),
// browserify = require('browserify'),
// sourceStream = require('vinyl-source-stream'),
connect = require('gulp-connect');
// Configure file paths
var path = {
DEST: 'dist/',
SRC: 'src/',
INCLUDES: 'include/',
LESS_SRC: 'src/frontend/less/',
LESS_MANIFEST: 'src/frontend/less/all.less',
CSS_DEST: 'dist/frontend/css/',
JS_SRC: 'src/frontend/js/',
JS_MINIFIED_OUT: 'all.js',
JS_DEST: 'dist/frontend/js',
IMG_SRC: 'src/frontend/img/',
IMG_DEST: 'dist/frontend/img/',
};
// Clean out build folder each time Gulp runs
gulp.task('clean', function (cb) {
del([
path.DEST
], cb);
});
// Compile LESS
gulp.task('less', function(){
return gulp.src(path.LESS_MANIFEST)
.pipe(watch(path.LESS_MANIFEST))
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(sourcemaps.init())
.pipe(less())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(path.CSS_DEST))
.pipe(connect.reload());
});
// Allow HTML files to be included
gulp.task('html', function() {
return gulp.src([path.SRC + '*.html'])
.pipe(watch(path.SRC + '*.html'))
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(fileinclude({
prefix: '##',
basepath: path.INCLUDES
}))
.pipe(gulp.dest(path.DEST))
.pipe(connect.reload());
});
// Concatenate and minify JavaScript
gulp.task('js', function() {
return gulp.src(path.JS_SRC + '**/*.js')
.pipe(watch(path.JS_SRC + '**/*.js'))
.pipe(order([
path.JS_SRC + 'framework/*.js',
path.JS_SRC + 'vendor/*.js',
path.JS_SRC + 'client/*.js'
], {base: '.'} ))
.pipe(concat(path.JS_MINIFIED_OUT))
.pipe(uglify())
.pipe(gulp.dest(path.JS_DEST))
.pipe(connect.reload());
});
// Minify images
gulp.task('imagemin', function () {
return gulp.src(path.IMG_SRC + '**/*')
.pipe(imagemin({
progressive: true,
use: [pngquant()]
}))
.pipe(gulp.dest(path.IMG_DEST));
});
// Copy folders
gulp.task('copy', function() {
gulp.src(path.SRC + 'extjs/**/*')
.pipe(gulp.dest(path.DEST + 'extjs/'));
// Copy all Bower components to build folder
gulp.src('bower_components/**/*')
.pipe(gulp.dest('dist/bower_components/'));
});
// Connect to a server and livereload pages
gulp.task('connect', function() {
connect.server({
root: path.DEST,
livereload: true
});
});
// Organize build tasks into one task
gulp.task('build', ['less', 'html', 'js', 'imagemin', 'copy']);
// Organize server tasks into one task
gulp.task('server', ['connect']);
// Default task
gulp.task('default', function(cb) {
// Clean out dist/ folder before everything else
runSequence('clean', ['build', 'server'],
cb);
});
Try and remove the watch from your build tasks, and have separate tasks that handle the watching. Something like:
gulp.task("watch-less", function() {
watch(path.LESS_MANIFEST, function () {
gulp.start("less");
));
});
That way, it'll just trigger the task when a file changes. And the task for watching is able to be run separate from your build (which will also make your life easier if you use some form of build automation).
Also, you can specify many watch tasks, like so:
gulp.task("watch", function() {
watch(paths.FOO, function() {
gulp.start("foo");
});
watch(paths.BAR, function() {
gulp.start("bar");
});
});

GulpJS copy folders and files from folder "foo" to folder "bar" and retain folder structure

I've got a folder "foo" and folder "bar", and I want to copy and run specific tasks on a specific files files.
Problem: I can copy files, run tasks on them and retain folder structure, but when I move files to folder "bar" it creates a folder "foo" inside folder "bar" and stores all copied files inside it.
Tried: Tried to change base: '.' to base: '../' but that just makes it compile everything to parent folder of bar.
Folder structure:
.
├── foo
│ ├── app.js
│ ├── models
│ ├── public
│ │ ├── images
│ │ └── js
│ ├── routes
│ └── scss
├── bar
│ └── ...
└── gulpfile.js
Gulpjs.js File:
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var sass = require('gulp-ruby-sass');
var cssmin = require('gulp-minify-css');
var rename = require('gulp-rename');
var htmlmin = require('gulp-htmlmin');
var paths = {
'ssjs' : ['foo/app.js', 'foo/routes/*.js', 'foo/models/*.js'],
'csjs' : ['foo/public/js/*.js'],
'sass' : ['foo/scss/*.scss', 'foo/scss/modules/*.scss'],
'html' : ['foo/public/*.html'],
'build' : 'bar',
'public': 'public'
};
gulp.task('ssjs', function() {
return gulp.src(paths.ssjs, {'base': '.'})
.pipe(uglify({'preserveComments': 'some'}))
.pipe(gulp.dest(paths.build));
});
gulp.task('csjs', function() {
return gulp.src(paths.csjs, {'base': '.'})
.pipe(uglify({'preserveComments': 'some'}))
.pipe(gulp.dest(paths.build));
});
gulp.task('sass', function() {
return gulp.src(paths.sass, {'base': '.'})
.pipe(sass())
.pipe(cssmin())
.pipe(gulp.dest(paths.build));
});
gulp.task('html', function() {
return gulp.src(paths.html, {'base': '.'})
.pipe(htmlmin({'collapseWhitespace': true}))
.pipe(gulp.dest(paths.build));
});
gulp.task('watch', function() {
gulp.watch(paths.ssjs, ['ssjs']);
gulp.watch(paths.csjs, ['csjs']);
gulp.watch(paths.scss, ['sass']);
});
gulp.task('default', [ 'ssjs', 'csjs', 'sass', 'html', 'watch' ]);
Solution: change 'base': '.' to 'base': 'foo'