gulp.watch() not running subsequent task - javascript

Running into a bizarre bug when trying to make modular gulp tasks by splitting them into separate files. The following should execute the task css, but does not:
File: watch.js
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
gulp.task('watch', function () {
plugins.watch('assets/styl/**/*.styl', ['css']); // PROBLEM
});
Declaring ['css'] in plugins.watch() should technically run the following task next:
File: css.js
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
gulp.task('css', function () {
return gulp.src('assets/styl/*.styl')
.pipe(plugins.stylus())
.pipe(gulp.dest('/assets/css'));
});
File: gulpfile.js
var gulp = require('gulp');
var requireDir = require('require-dir');
requireDir('./gulp/tasks', { recurse: true });
gulp.task('develop', ['css', 'watch']);
Folder structure
- gulp/
- tasks/
- css.js
- watch.js
- gulpfile.js
Expected behavior
gulp develop should run tasks css and watch (it does). On file changes, watch should detect them (it does) and then run the css task (it's does not).
One solution
Not terribly fond of this solution as gulp.start() is being deprecated in the next release, but this does fix it:
File: watch.js
plugins.watch('assets/styl/**/*.styl', function() {
gulp.start('css');
});

Either use gulp's builtin watch with this syntax:
gulp.task('watch', function () {
gulp.watch('assets/styl/**/*.styl', ['css']);
});
Or gulp-watch plugin with this syntax:
gulp.task('watch', function () {
plugins.watch('assets/styl/**/*.styl', function (files, cb) {
gulp.start('css', cb);
});
});
There's also probably a typo in your gulp.dest path. Change it to relative:
.pipe(gulp.dest('assets/css'));

I am using Gulp 4, where gulp.start() is deprecated
So here's the solution
gulp.task('watch', gulp.series('some-task-name', function () {
browserSync.init({
server: {
baseDir: config.distFolder + ''
}
});
var watcher = gulp.watch([
'./src/views/*.html',
'./src/index.html',
'./src/assets/css/*.css',
'./src/**/*.js'],
gulp.series('some-task-name'));
watcher.on('change', async function (path, stats) {
console.log('you changed the code');
browserSync.notify("Compiling, please wait!");
browserSync.reload();
})
}));
Now, whenever there is a change in my code, my "some-task-name" gets executed and then the browser page is reloaded. I don't need to delay my browser-sync at all.

Related

Local changes to file in node_modules (Angular 2)

I know that this can be a very stupid question, but I can't find matches with other posts on stackoverflow...
So: Can I modify a file of an external module , just save the file and do something that my app can listen?
At the moment, i'm trying ti change some scss style at the ng2-datepicker module (inside node_modules folder), but if I save and the launch ng serve, changes will not affect my project.
I know it's a simple problem, but i don't know the background architecture of an Angular2 project.
Thanks in advance.
(ps I've seen that i can fork the git and then do something like npm install.
Very interesting, but i also want to know how to have the same result in local)
If you are using gulp file you can tell the changed lib file path to copy to build folder check gulp.task('copy-libs') in code below git repo for angular2-tour-of-heroes using gulp
const gulp = require('gulp');
const del = require('del');
const typescript = require('gulp-typescript');
const tscConfig = require('./tsconfig.json');
const sourcemaps = require('gulp-sourcemaps');
const tslint = require('gulp-tslint');
const browserSync = require('browser-sync');
const reload = browserSync.reload;
const tsconfig = require('tsconfig-glob');
// clean the contents of the distribution directory
gulp.task('clean', function () {
return del('dist/**/*');
});
// copy static assets - i.e. non TypeScript compiled source
gulp.task('copy:assets', ['clean'], function() {
return gulp.src(['app/**/*', 'index.html', 'styles.css', '!app/**/*.ts'], { base : './' })
.pipe(gulp.dest('dist'))
});
// copy dependencies
gulp.task('copy:libs', ['clean'], function() {
return gulp.src([
'node_modules/angular2/bundles/angular2-polyfills.js',
'node_modules/systemjs/dist/system.src.js',
'node_modules/rxjs/bundles/Rx.js',
'node_modules/angular2/bundles/angular2.dev.js',
'node_modules/angular2/bundles/router.dev.js',
'node_modules/node-uuid/uuid.js',
'node_modules/immutable/dist/immutable.js'
'yourpath/changedFileName.js'
])
.pipe(gulp.dest('dist/lib'))
});
// linting
gulp.task('tslint', function() {
return gulp.src('app/**/*.ts')
.pipe(tslint())
.pipe(tslint.report('verbose'));
});
// TypeScript compile
gulp.task('compile', ['clean'], function () {
return gulp
.src(tscConfig.files)
.pipe(sourcemaps.init())
.pipe(typescript(tscConfig.compilerOptions))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/app'));
});
// update the tsconfig files based on the glob pattern
gulp.task('tsconfig-glob', function () {
return tsconfig({
configPath: '.',
indent: 2
});
});
// Run browsersync for development
gulp.task('serve', ['build'], function() {
browserSync({
server: {
baseDir: 'dist'
}
});
gulp.watch(['app/**/*', 'index.html', 'styles.css'], ['buildAndReload']);
});
gulp.task('build', ['tslint', 'compile', 'copy:libs', 'copy:assets']);
gulp.task('buildAndReload', ['build'], reload);
gulp.task('default', ['build']);

BrowserSync refreshing before injection (Gulp)

I have my gulpfile:
var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var sourcemaps = require('gulp-sourcemaps');
var fileinclude = require('gulp-file-include');
var browserify = require('browserify');
var rename = require('gulp-rename');
var streamify = require('gulp-streamify'); // required for uglify
var uglify = require('gulp-uglify'); // minify JS
var source = require('vinyl-source-stream'); // required to dest() for browserify
var browserSync = require('browser-sync').create();
var localSettings = require('./gulp/localConfig.js');
gulp.task('sass', function () {
return gulp.src('./assets/sass/main.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError)) // .on('error', sass.logError) prevents gulp from crashing when saving a typo or syntax error
.pipe(sourcemaps.write())
.pipe(gulp.dest('./assets/sass'))
.pipe(browserSync.stream()); // causes injection of styles on save
});
gulp.task('compileHTML', function() {
return gulp.src(['static/src/*.html'])
.pipe(fileinclude({
prefix: '##',
basepath: '#root'
}))
.pipe(gulp.dest('./static/compiled'))
.pipe(browserSync.stream()); // causes injection of html changes on save
});
// Static Server for browsersync
gulp.task('sync', ['sass'], function() {
browserSync.init({
startPath: "static/compiled/index.html",
open: localSettings.openBrowserSyncServerOnBuild,
server: {
baseDir: "./",
}
});
});
gulp.task('watch', function() {
gulp.watch('./assets/sass/**/*.scss', ['sass']);
gulp.watch(['./static/src/**/*.html', '!partials', '!components'], ['compileHTML']);
gulp.watch('./assets/js/**/*.js', ['javascript']);
});
gulp.task('javascript', function() {
var bundleStream = browserify('./assets/js/main.js').bundle();
bundleStream
.pipe(source('main.js'))
.pipe(rename('bundle.js'))
.pipe(gulp.dest('./assets/js/'))
.pipe(browserSync.stream());
})
// Default Task
gulp.task('default', ['compileHTML', 'javascript', 'sass', 'watch', 'sync']);
Mostly everything with my build works great, however I am having one issue with my compileHTML task. When any modifications are made to my html, it is compiled and injected into the page with BrowserSync. The problem is that BrowserSync is injecting the markup into the page AFTER it reloads, so that I have to manually refresh or save the file again.
Although I am doing the exact same thing with my SASS task, I have no problems with that task. Why do my styles inject into the page before the reload, but the HTML does not?
Just for testing, I tried adding a setTimout surrounding the BrowserSync injection, but it did not affect the timing of the injection other than adding a delay.
I would try to follow the example at gulp-reload docs. Their example is:
// create a task that ensures the `js` task is complete before
// reloading browsers
gulp.task('js-watch', ['js'], function (done) {
browserSync.reload();
done();
});
So you try :
gulp.watch(['./static/src/**/*.html', '!partials', '!components'], ['compileHTML'],
function (done) {
browserSync.reload();
done();
});
And remove the pipe browserSync.stream() in your 'complieHTML' task.
[I might first try as a very simple attempt changing from stream() to reload() in that task before the changes above.]

Gulp concat and minify with a watch task

I'm trying to setup a some Gulp tasks. I want to concatenate some JS files, minify them to create 1 JS file, but I want this done each time a change has been made in the original JS files but I can't seem to get the 'watch' task running properly
This is my Gulpfile.js
gulp.task('minify', ['watch', 'scripts'], function(){
gulp.src('themes/corp-fluid/js/dist/**/*.js')
.pipe(minify({
ext:{
src:'-debug.js',
min:'.js'
},
ignoreFiles: ['-min.js']
}))
.pipe(gulp.dest('themes/corp-fluid/js/dist'));
});
gulp.task('scripts', function(){
return gulp.src(['themes/corp-fluid/js/slick.js', 'themes/corp-fluid/js/functions.js'])
.pipe(concat('main.js'))
.pipe(gulp.dest('themes/corp-fluid/js/dist'));
});
gulp.task('watch', function(){
gulp.watch('themes/corp-fluid/js/**/*.js');
});
A couple of things. You need to call something in your
'watch' task, so
gulp.task('watch', function(){
gulp.watch('themes/corp-fluid/js/**/*.js', ['minify']);
});
and simplify the first line of your 'minify' task to
gulp.task('minify', ['scripts'], function(){
you don't need to call the 'watch' task again there. And finally you would be running the whole thing with
gulp watch
Gulpfile with sass, js concat, minify, and watch task.
You need change proxy domain name to yor domain name in browser-sync task, and change array of files in concat_js task.
var gulp = require('gulp')
var browserSync = require('browser-sync')
var sass = require('gulp-sass')
var concat = require('gulp-concat');
var minify = require('gulp-minify');
//Sass
gulp.task('sass', function () {
return gulp.src('app/sass/**/*.scss')
.pipe(sass())
// pipe(gulp.dest('app/css'))
.pipe(gulp.dest('app/css/'))
});
//browser reload
gulp.task('browser-sync', function () {
browserSync({
notify: false,
proxy: "http://front-end" //Your domain name
});
});
//concat
gulp.task('concat_js', function() {
//An array of files is required for the correct order of contact
return gulp.src(['app/js/_helpers.js',
'app/js/_cookie_notice.js']) //file array need for
.pipe(concat('all.js'))
.pipe(minify({
ext:{
src:'',
min:'.min.js'
},
noSource: true}))
.pipe(gulp.dest('app/js/'));
});
//watch
gulp.task('watch', ['browser-sync', 'sass'], function () {
gulp.watch('app/sass/**/*.scss', ['sass']);
gulp.watch('app/js/*.js', ['concat_js']);
gulp.watch('app/**/*.*', browserSync.reload);
});
gulp.task('default', ['watch', 'sass', 'concat_js']);
Note: An array of files in task concat_js is required for the correct order of file contact.

How to tell gulp.watch to wait until necessary tasks will not be finished before running new cycle?

I have an issue with gulp.watch.
TLDR:
How to tell gulp.watch to wait until necessary tasks will not be finished before running new cycle?
Reasons:
I have three tasks: clean, build, and watch.
Task clean deletes directory, task build produces files in the same directory (clean is dependency for build).
Task watch runs gulp.watch on directory and then it runs build (that runs clean).
But sometimes watch task runs new build before previous build is finished and an error occurs: build continues write to directory and clean tries to remove directory (of course, ENOTEMPTY error happens).
This issue happens when I run gulp watch command.
My Gulpfile.js:
var gulp = require('gulp');
var ts = require('gulp-typescript');
var tslint = require('gulp-tslint');
var rename = require('gulp-rename');
var del = require('del');
var tsProject = ts.createProject('tsconfig.json');
var tsSources = ['app/**/*.ts', 'app/**/*.tsx'];
gulp.task('clean', function() {
return del(['built']);
});
gulp.task('build', ['clean'], function() {
return gulp.src(tsSources)
.pipe(ts(tsProject)).js
.pipe(rename({extname: '.js'}))
.pipe(gulp.dest('built'));
});
gulp.task('tslint', ['clean'], function() {
return gulp.src(tsSources)
.pipe(tslint())
.pipe(tslint.report('msbuild', {
emitError: false,
summarizeFailureOutput: false
}));
});
gulp.task('watch', ['build', 'tslint'], function() {
return gulp.watch(tsProject.config.filesGlob, ['build', 'tslint']);
});
gulp.task('default', ['build', 'tslint']);
For cleaning the gulp use following code:-
gulp.task('clean', function() {
del.sync([
path.join(__dirname, builtPath, '**/*.js'),
], {
force: true
});
});

Nodemon restart run gulp tasks

I have the following code in my gulpfile
gulp.task('scripts', function () {
gulp.src(paths.browserify)
.pipe(browserify())
.pipe(gulp.dest('./build/js'))
.pipe(refresh(server));
});
gulp.task('lint', function () {
gulp.src(paths.js)
.pipe(jshint())
.pipe(jshint.reporter(stylish));
});
gulp.task('nodemon', function () {
nodemon({
script: 'app.js'
});
});
I need to run the scripts and lint tasks when Nodemon restarts.I have the following
gulp.task('nodemon', function () {
nodemon({
script: 'app.js'
}).on('restart', function () {
gulp.run(['scripts', 'lint']);
});
});
Gulp.run() is now deprecated, so how would I achieve the above using gulp and best practices?
gulp-nodemon documentation states that you can do it directly, passing an array of tasks to execute:
nodemon({script: 'app.js'}).on('restart', ['scripts', 'lint']);
See doc here
UPDATE, as the author of gulp-nodemon uses run as well:
Idea #1, use functions:
var browserifier = function () {
gulp.src(paths.browserify)
.pipe(browserify())
.pipe(gulp.dest('./build/js'))
.pipe(refresh(server));
});
gulp.task('scripts', browserifier);
var linter = function () {
gulp.src(paths.js)
.pipe(jshint())
.pipe(jshint.reporter(stylish));
});
gulp.task('lint', linter);
nodemon({script: 'app.js'}).on('restart', function(){
linter();
browserifier();
});
If you can, use Mangled Deutz's suggestion about using functions. That's the best, most guaranteed way to make sure this works now and going forward.
However, functions won't help if you need to run dependent tasks or a series of tasks. I wrote run-sequence to fix this. It doesn't rely on gulp.run, and it's able to run a bunch of tasks in order.

Categories

Resources