I have a problem with my gulp, I don't know how to explain it, but you will understand the problem when you see it, basically, I think my gulp is duplicating the task and therefore the execution can take a while, but if I finish the gulp and execute it again, the problem does not happen the first time it is compiled, but over time it is repeated more and more (first doubles, then 4x, 8x and so on)
my gulp:
var gulp = require('gulp'),
//Js
babel = require('gulp-babel');
uglify = require('gulp-uglify'),
filesJs = './js/edit/*.js',
outputJs = './js',
//Sass
sass = require('gulp-sass'),
filesCss = './css/**/*.+(scss|sass)',
outputCss = './css';
const {
watch
} = require('gulp');
//Uglify
gulp.task('uglify', function () {
gulp.src(filesJs)
.pipe(babel({presets: ['#babel/preset-env']}))
.pipe(uglify())
.pipe(gulp.dest(outputJs));
});
const watcherJS = watch([filesJs]);
watcherJS.on('change', function (path, stats) {
console.log(`File ${path} was changed`);
return gulp.watch(filesJs, gulp.series('uglify'));
});
//Sass
gulp.task('sass', function () {
return gulp.src(filesCss)
.pipe(sass({
outputStyle: 'compressed'
}).on('error', sass.logError))
.pipe(gulp.dest(outputCss));
});
const watcherCSS = watch([filesCss]);
watcherCSS.on('change', function (path, stats) {
console.log(`File ${path} was changed`);
return gulp.watch(filesCss, gulp.series('sass'));
});
//Run/Watch
gulp.task('default', gulp.parallel('uglify', 'sass'));
my terminal after a save the .sass file once
File css\style.sass was changed
[09:43:18] Starting 'sass'...
[09:43:18] Starting 'sass'...
[09:43:18] Starting 'sass'...
[09:43:18] Starting 'sass'...
[09:43:33] Finished 'sass' after 15 s
[09:43:33] Finished 'sass' after 15 s
[09:43:33] Finished 'sass' after 15 s
[09:43:33] Finished 'sass' after 15 s
It is almost certainly your use of the chokidar watch functionality. Your code won't even run for me. And you don't need that complexity. I suggest getting rid of
const watcherJS = watch([filesJs]);
watcherJS.on('change', function (path, stats) {
console.log(`File ${path} was changed`);
return gulp.watch(filesJs, gulp.series('uglify')); // this is very strange, must be wrong
});
const watcherCSS = watch([filesCss]);
watcherCSS.on('change', function (path, stats) {
console.log(`File ${path} was changed`);
return gulp.watch(filesCss, gulp.series('sass'));
});
and replacing with:
gulp.task('watchFiles', function () {
gulp.watch(filesCss, gulp.series('sass'));
gulp.watch(filesJs, gulp.series('uglify'));
});
and using
gulp.task('default', gulp.series('uglify', 'sass', 'watchFiles'));
Related
$ gulp build
[02:36:37] Using gulpfile C:\xampp\htdocs\melodic\gulpfile.js
[02:36:37] Starting 'build'...
[02:36:37] Starting 'clean:dist'...
[02:36:37] Finished 'clean:dist' after 4.63 ms
[02:36:37] Starting 'sass'...
[02:36:37] Starting 'useref'...
[02:36:37] Starting 'img'...
[02:36:37] Starting 'cleancss'...
[02:36:37] Finished 'cleancss' after 37 ms
C:\xampp\htdocs\melodic\node_modules\gulp-useref\node_modules\vinyl-
fs\lib\src\index.js:20
throw new Error('Invalid glob argument: ' + glob);
^
Error: Invalid glob argument:
at Object.src (C:\xampp\htdocs\melodic\node_modules\gulp-
useref\node_modules\vinyl-fs\lib\src\index.js:20:11)
at DestroyableTransform.addAssetsToStream
(C:\xampp\htdocs\melodic\node_modules\gulp-useref\index.js:62:15)
at C:\xampp\htdocs\melodic\node_modules\gulp-useref\index.js:124:31
at Array.forEach (native)
at DestroyableTransform.processAssets
(C:\xampp\htdocs\melodic\node_modules\gulp-useref\index.js:115:11)
at C:\xampp\htdocs\melodic\node_modules\gulp-useref\index.js:178:31
at Stream.<anonymous> (C:\xampp\htdocs\melodic\node_modules\gulp-
useref\node_modules\event-stream\index.js:318:20)
at _end (C:\xampp\htdocs\melodic\node_modules\through\index.js:65:9)
at Stream.stream.end
(C:\xampp\htdocs\melodic\node_modules\through\index.js:74:5)
at DestroyableTransform.onend
(C:\xampp\htdocs\melodic\node_modules\through2\node_modules\readable-
stream\lib\_stream_readable.js:577:10)
I have tried to remove the running tasks one by one but to no avail. What throws me off also is the fact that it seems to run through all the tasks and even finishing them and then crashing as the last task is finished. Thanks in advance.
EDIT: Here is my gulpfile as I forgot to include it.
var gulp = require('gulp');
// Requires the gulp-sass plugin
var sass = require('gulp-sass');
//Requires browser synch
var browserSync = require('browser-sync').create();
//Requires userref
var useref = require('gulp-useref');
//Requires uglify
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
//Requires cssnano
var cssnano = require('gulp-cssnano');
//Requires imagemin
var imagemin = require('gulp-imagemin');
//Requires cache
var cache = require('gulp-cache');
//Requires del
var del = require('del');
//Requires run-sequence
var runSequence = require('run-sequence');
//requires postcss
var postcss = require('gulp-postcss');
//ACTIVE COMMANDS
/*Run 'gulp browserSync' in commandline.
This task automatically reloads the broswer upon each save of document*/
gulp.task('browserSync', function() {
browserSync.init({
injectChanges: true,
server: {
baseDir: "./app"
},
})
});
/*Run 'gulp sass' in command line.
THIS TASK GETS ALL SCSS IMPORTED INTO THE app.scss FILE AND CONVERTS IT INTO app.css.
THIS TASK IS A ONE TIME CONVERSTION*/
gulp.task('sass', function() {
return gulp.src('app/scss/**/*.scss') // Gets all files ending with .scss in app/scss
.pipe(sass())
.pipe(gulp.dest('app/css'))
.pipe(browserSync.stream({match: '**/*.css'}));
});
/*Run 'gulp watch' in command line.
THIS TASK GETS ALL SCSS AND OTHER FILE TYPES AND CONVERTS THEM ACITVELY.
THIS TASK IS ONGOING*/
gulp.task('watch', ['browserSync', 'sass'], function (){
gulp.watch('app/scss/**/*.scss', ['sass']);
});
//PRODUCTION/FINAL COMMANDS
/*Run 'gulp useref' in command line.
THIS TASK GETS ALL CSS AND OTHER FILE TYPES AND JOINS DIFFERENT FILES AND MINIMIZES THEM IN THE DIST FOLDER.
*/
gulp.task('useref', function(){
return gulp.src('app/*.html')
.pipe(useref())
// Minifies only if it's a JavaScript file
.pipe(gulpIf('*.js', uglify()))
// Minifies only if it's a CSS file
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('dist'))
});
gulp.task('cleancss', function () {
return gulp.src('./src/*.css')
.pipe(postcss())
.pipe(gulp.dest('./dest'));
});
/*Run 'gulp img' in command line.
MINIMIZSES PHOTOS TO THE DIST FOLDER*/
gulp.task('img', function(){
return gulp.src('app/img/**/*.+(png|jpg|gif|svg)')
.pipe(imagemin({
// Setting interlaced to true
interlaced: true
}))
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true
})))
.pipe(gulp.dest('dist/img'))
});
/*Run 'gulp fonts' in command line.
CLEANS THE DIST DIRECTORY FOR UNUSED FILES*/
gulp.task('clean:dist', function() {
return del.sync('dist');
});
/*Run 'gulp fonts' in command line.
CLEANS THE IMAGE CACHE CREATED EARLIER*/
gulp.task('cache:clear', function (callback) {
return cache.clearAll(callback)
});
gulp.task('build', function (callback) {
runSequence('clean:dist',
['sass', 'useref', 'img', 'cleancss'],
callback
)
});
gulp.task('default', function (callback) {
runSequence(['sass','browserSync', 'watch'],
callback
)
});
EDIT: Included my gulpfile for further details.
Problems I'm facing:
The browser doesn't reflect live changes in .scss or .js
I don't understand whether we have to return the stream from the gulp.task() or not, I visited some websites and watched lectures some of which used return and some didn't.
Cannot understand the flow of execution of gulpfile (which statement runs first, then which and so on)
This is my current code of gulpfile.js.
"use strict";
var gulp = require('gulp');
var sass = require('gulp-sass');
var nodemon = require('gulp-nodemon');
var browserSync = require('browser-sync').create();
var uglify = require('gulp-uglify');
gulp.task('default', ['nodemon'], function(){
gulp.watch("src/sass/*.scss", ['sass']);
gulp.watch("src/js/*.js", ['js']);
gulp.watch("views/*.ejs").on('change',browserSync.reload); //Manual Reloading
})
// Process JS files and return the stream.
gulp.task('js', function () {
return gulp.src('src/js/*.js')
.pipe(uglify())
.pipe(gulp.dest('public/javascripts'));
});
// Compile SASS to CSS.
gulp.task('sass', function(){
// gulp.src('src/sass/*.scss') //without return or with return? why?
return gulp.src('src/sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('public/stylesheets'))
.pipe(browserSync.stream());
});
// Setup proxy for local server.
gulp.task('browser-sync', ['js','sass'], function() {
browserSync.init(null, {
proxy: "http://localhost:3000",
port: 7000,
});
});
gulp.task('nodemon', ['browser-sync'], function(cb){
var running = false;
return nodemon({script: 'bin/www'}).on('start', function(){
if(!running)
{
running = true;
cb();
}
});
})
You may look at project structure at https://github.com/DivyanshBatham/GulpWorkflow
Try this:
"use strict";
var gulp = require('gulp');
var sass = require('gulp-sass');
var nodemon = require('gulp-nodemon');
var browserSync = require('browser-sync').create();
var uglify = require('gulp-uglify');
// First, run all your tasks
gulp.task('default', ['nodemon', 'sass', 'js'], function(){
// Then watch for changes
gulp.watch("src/sass/*.scss", ['sass']);
gulp.watch("views/*.ejs").on('change',browserSync.reload); //Manual Reloading
// JS changes need to tell browsersync that they're done
gulp.watch("src/js/*.js", ['js-watch']);
})
// create a task that ensures the `js` task is complete before
// reloading browsers
gulp.task('js-watch', ['js'], function (done) {
browserSync.reload();
done();
});
// Process JS files and return the stream.
gulp.task('js', function () {
return gulp.src('src/js/*.js')
.pipe(uglify())
.pipe(gulp.dest('public/javascripts'));
});
// Compile SASS to CSS.
gulp.task('sass', function(){
return gulp.src('src/sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('public/stylesheets'))
.pipe(browserSync.stream());
});
// Setup proxy for local server.
gulp.task('browser-sync', ['js','sass'], function() {
browserSync.init(null, {
proxy: "http://localhost:3000",
port: 7000,
});
});
gulp.task('nodemon', ['browser-sync'], function(cb){
var running = false;
return nodemon({script: 'bin/www'}).on('start', function(){
if(!running)
{
running = true;
cb();
}
});
})
Also, you should consider adding the JS file to your index.ejs
Eg: <script src='/javascripts/main.js'></script>
More help: https://browsersync.io/docs/gulp
I'll answer what I can.
You don't always have to return the stream in a gulp task but you should since you have some tasks, like 'browser-sync' that are dependent on other tasks, ['js','sass'], finishing. The purpose of returning the stream is to signal task completion. It is not the only way to signal task completion but one easy way.
You are already doing this in your ['js','sass'] tasks with the return statements.
Your 'js' task needs a .pipe(browserSync.stream()); statement at the end of it like your 'sass' task. Or try .pipe(browserSync.reload({stream:true})); sometimes that variant works better.
You have both browser-sync and nodemon running - that I believe is unusual and may cause problems - they do much the same thing and do not typically see them running together. I would eliminate nodemon from your file.
Flow of execution:
(a) default calls ['nodemon', 'sass', 'js'] : these run in parallel.
(b) nodemon call 'browser-sync'. 'browserSync' must finish setting up before 'nodemon' gets into its function.
(c) 'browser-sync', ['js','sass'], Here browser-sync is dependent upon 'js' and 'sass' which run in parallel and must finish and signal that they have finished by returning the stream for example before browser-sync continues.
(d) After 'js', 'sass', 'browser-sync' and 'nodemon' have completed, your watch statements are set up and begin to watch.
I have a gulp file using gulp-git that I wrote to assist our content writers in pushing their updates without having to use git command line. So basically it watches for changes in the given directories and then adds, commits, and pushes the changes.
The gulp file is this:
var gulp = require('gulp');
var git = require('gulp-git');
var runSequence = require('run-sequence');
gulp.task('add', function() {
return gulp.src('./*')
.pipe(git.add({args: '-A'}))
})
gulp.task('add-blog', function() {
return gulp.src([
'./post',
'./properties',
'./files',
'./files'
])
.pipe(git.add())
})
gulp.task('commit-blog', function() {
return gulp.src([
'./post',
'./properties',
'./files'
])
.pipe(git.commit('blog commit'))
})
gulp.task('push', function() {
git.push('origin', function(err) {
if (err) throw err;
});
})
gulp.task('deploy', function(done) {
runSequence('add-blog', 'commit-blog', 'push');
});
gulp.task('watch', function () {
gulp.watch([
'./post/*',
'./properties/*',
'./files/*'
], ['deploy'])
});
then I run:
$nohup gulp watch &
it seems to run, but when I look at nohup out i see:
[16:12:37] Using gulpfile /var/www/html/respond/app/sites/ohio-cashflow/gulpfile.js
[16:12:37] Starting 'watch'...
[16:12:38] Finished 'watch' after 1.09 s
and it never runs the git commands when files are added or changed in the appropriate directories?
What am I missing here?
I have a pretty simple and straightforward gulpfile for sass compilation, concat, minification and browser reload on changes using a watch task that observes for *.php, *.js and *.sass.
require('es6-promise').polyfill();
var gulp = require('gulp'),
sass = require('gulp-sass');
var concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
livereload = require('gulp-livereload');
var config = {
scripts: [
'./bower_components/jquery/dist/jquery.min.js',
'./bower_components/materialize/dist/js/materialize.js',
'./js/**/*.js'
]
};
gulp.task('sass', function() {
return gulp.src('./sass/style.scss')
.pipe(sass.sync({
includePaths: ['./bower_components/materialize/sass'],
outputStyle: 'compressed'
}).on('error', sass.logError))
.pipe(livereload())
.pipe(gulp.dest('./'));
});
gulp.task('scripts', function() {
return gulp.src(config.scripts)
.pipe(concat('scripts.js'))
.pipe(gulp.dest('./js/'))
.pipe(uglify())
.pipe(rename({
extname: '.min.js'
}))
.pipe(livereload())
.pipe(gulp.dest('./js/'));
});
gulp.task('copyassets', function(){
})
// default task
gulp.task('default', ['sass', 'scripts']);
gulp.task('watch', function () {
livereload.listen(35729);
gulp.watch('**/*.php').on('change', function(file) {
livereload.changed(file.path);
});
gulp.watch('./sass/**/*.scss', ['sass']);
gulp.watch('./js/**/*.js', ['scripts']);
});
I execute the default task with gulp, and it was working fine for me until a few hours ago. All of a sudden, I have started getting FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory on SASS changes.
I have tried allocating it more space with '--max-old-space-size=8192', but to no use.
I have reverted all recent changes too in my code base, but that did not seem to fix it too.
Any help or pointers will be appreciated.
I am using this in combination with a _s WP theme.
What is the proper way to use gulp-watch plugin?
...
var watch = require('gulp-watch');
function styles() {
return gulp.src('app/styles/*.less')
.pipe(watch('app/styles/*.less'))
.pipe(concat('main.css'))
.pipe(less())
.pipe(gulp.dest('build'));
}
gulp.task('styles', styles);
I don't see any results when run gulp styles.
In your shell (such as Apple's or Linux's Terminal or iTerm) navigate to the folder that your gulpfile.js. For example, if you're using it with a WordPress Theme your gulpfile.js should be in your Theme's root. So navigate there using cd /path/to/your/wordpress/theme.
Then type gulp watch and hit enter.
If your gulpfile.js is configured properly (see example below) than you will see output like this:
[15:45:50] Using gulpfile /path/to/gulpfile.js
[15:45:50] Starting 'watch'...
[15:45:50] Finished 'watch' after 11 ms
Every time you save your file you'll see new output here instantly.
Here is an example of a functional gulpfile.js:
var gulp = require('gulp'),
watch = require('gulp-watch'),
watchLess = require('gulp-watch-less'),
pug = require('gulp-pug'),
less = require('gulp-less'),
minifyCSS = require('gulp-csso'),
concat = require('gulp-concat'),
sourcemaps = require('gulp-sourcemaps');
gulp.task('watch', function () {
gulp.watch('source/less/*.less', ['css']);
});
gulp.task('html', function(){
return gulp.src('source/html/*.pug')
.pipe(pug())
.pipe(gulp.dest('build/html'))
});
gulp.task('css', function(){
return gulp.src('source/less/*.less')
.pipe(less())
.pipe(minifyCSS())
.pipe(gulp.dest('build/css'))
});
gulp.task('js', function(){
return gulp.src('source/js/*.js')
.pipe(sourcemaps.init())
.pipe(concat('app.min.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('build/js'))
});
gulp.task('default', [ 'html', 'js', 'css', 'watch']);
Note: Anywhere you see source/whatever/ this is a path you'll either need to create or update to reflect the path you're using for the respective file.
gulp.task('less', function() {
gulp.src('app/styles/*.less')
.pipe(less())
.pipe(gulp.dest('build'));
});
gulp.task('watch', function() {
gulp.watch(['app/styles/*.less'], ['less'])
});
Name your task like I have my 'scripts' task named so you can add it to the series. You can add an array of tasks to the series and they will be started in the order they are listed. For those coming from prior versions note the return on the gulp.src.
This is working code I hope it helps the lurkers.
Then (for version 4+) you need to do something like this:
var concat = require('gulp-concat'); // we can use ES6 const or let her just the same
var uglify = require('gulp-uglify'); // and here as well
gulp.task('scripts', function(done) {
return gulp.src('./src/js/*.js')
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(gulp.dest('./dist/js/'));
});
gulp.task('watch', function() {
gulp.watch('./src/js/*.js',gulp.series(['scripts']))
});
** Note the line gulp.watch('./src/js/*.js',gulp.series(['scripts'],['task2'],['etc']))