I'm new to Gulp and I found a Gulpfile.js example I wanted to use to livereload my express app's server whenever a change takes place in either my app.js file or ./public directory. Here is the Gulpfile.js code:
var gulp = require('gulp'),
spawn = require('child_process').spawn,
node;
/**
* $ gulp server
* description: Launch the server. If there's a server already running, kill it.
*/
gulp.task('server', function() {
if (node) node.kill()
node = spawn('node', ['app.js'], {stdio: 'inherit'})
node.on('close', function (code) {
if (code === 8) {
gulp.log('Error detected, waiting for changes...');
}
});
})
/**
* $ gulp default
* description: Start the development environment
*/
gulp.task('default', function() {
gulp.run('server')
gulp.watch(['./app.js', './public/'], function() {
gulp.run('server')
})
})
// clean up if an error goes unhandled.
process.on('exit', function() {
if (node) node.kill()
})
In my terminal window I keep getting the following warning:
gulp.run() has been deprecated. Use task dependencies or gulp.watch task triggering instead.
Gulp is working and it is livereloading the web application like I want it to but I'd like to fix this issue to future proof my development process, as well as get rid of this annoying warning message.
Thanks for the help!
One option would be to simply replace all occurrences of gulp.run() with gulp.start():
gulp.task('default', function() {
gulp.start('server');
gulp.watch(['./app.js', './public/'], function() {
gulp.start('server');
});
});
However calling a task explicitly using gulp.start() is not the idiomatic way of doing things in gulp (although sometimes it's necessary).
The warning message you receive already hints at the idiomatic way of solving this:
Use task dependencies or gulp.watch task triggering
Task dependencies allow you to run a task before another task. That means you can get rid of the first gulp.run().
Task triggering in gulp.watch() allows you to run a task when a file changes. That means you can get rid of the second gulp.run().
Therefore your default task ends up looking like this:
gulp.task('default', ['server'], function() {
gulp.watch(['./app.js', './public/'], ['server']);
});
Related
I want to put inside gulpfile something like:
require('web-component-tester').gulp.init(gulp);
gulp.task('default', function() {
gulp.watch(['elements/**', 'test/**'], ['test:local']);
});
The purpose is to watch test folders or elements folders (with Polymer components). If some of them will change, run test with each build.
my wct.conf.js:
module.exports = {
root: '.tmp/elements/',
suites: ['**/test/'],
plugins: {
local: {browsers: ['chrome']},
}
};
I found the code above on some page but after I add some tests and then type gulp in my terminal I found error, because .tmp folder is not updated and strange errors like Polymer is not definedor ajax.generateRequest is not a function. I got also right errors when I intentionally made a mistake in a test to fail it, so it looks like something is ok, but not at all.
I add the tests to the existing project with lots of files. When I tried to do the same thing on empty project I also got the same error until I type bower install.
Is there any chance that this is the problem with bower dependencies?
Or have you any idea what is wrong? Is this part of code in gulpfile right to perform the desired effect?
Thanks a lot.
I am not answering your question directly, because its been a while since I've done it that way. But the following defines a sub task from among others to define a task called 'client' which then runs the tests in a frame buffer (so I don't have disturbing windows popping up all over the place when the tests run - they just run and output in a console window. Its effectively spawning a command line version of wct and I don't have a wct.conf file at all.
(function() {
'use strict';
const spawn = require('child_process').spawn;
module.exports = function(gulp) {
gulp.task('test:client',['lint:client'], () => {
var child = spawn('xvfb-run', ['-a', 'wct', '--color'], {cwd: process.cwd()});
child.stdout.setEncoding('utf8');
child.stdout.on('data', function(data) {
process.stdout.write(data);
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', function(data) {
process.stderr.write(data);
});
});
gulp.task('client',function() {
gulp.watch([
'app/index.html',
'app/src/*.html',
'app/test/*.html',
'aoo/mocks/*.html',
'gulpfile.js',
'tasks/*.js'
],['test:client']);
});
};
})();
This file is one file within the tasks directory (which as you can see I am watching)
My gulpfile loads this, and other tasks like so (I copied this from the angular.js team who used it to load some of there tasks supporting angular)
(function() {
'use strict';
require('dotenv').config(); //load our environment
var gulp = require('gulp');
var includeAll = require('include-all');
/**
* Loads task modules from a relative path.
*/
function loadTasks(relPath) {
return includeAll({
dirname: require('path').resolve(__dirname, relPath),
filter: /(.+)\.js$/
}) || {};
}
// *
// * Invokes the function from a Gulp configuration module with
// * a single argument - the `gulp` object.
function addTasks(tasks) {
for (var taskName in tasks) {
if (tasks.hasOwnProperty(taskName)) {
tasks[taskName](gulp);
}
}
}
/**
* Add all Gulp tasks to the gulpfile.
* Tasks are in `tasks/`
*/
addTasks(loadTasks('tasks/'));
// require('gulp-load-tasks')(__dirname + '/tasks');
gulp.task('default', ['lint:gulp','client','server']);
})();
I am trying to create a gulp task that updates all the assets in my project by executing a shell script. The problem is that it executes as expected and then just hangs.
'use-strict';
var gulp = require('gulp'),
gutil = require('gulp-util');
exec = require('child_process').exec;
var foreach = require('gulp-foreach');
gulp.task('update-assets', function () {
exec('./update_assets.sh', {cwd: 'assets'}, function(err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
});
gulp.task('default', ['update-assets'], function() {
gulp.start('update-assets');
});
This is because of the nature of exec(). What exec() does it allows the command you give it to "take over" the current process. What you can do is instead try something like child_process.spawn . If it is a daemon process.
Take a good look at the Child_Process documentation. I think that this should help you get a good start.
Other options that may be helpful include modifying the script to throw exit codes for Gulp to recognize, or using timeouts to know when a gulp task has terminated.
UPDATE: Alternatively, you could use this, which is what I found worked for me when running a web server.
shell.exec('./update_assets.sh', {async:true} );
Running the out of the box 'protractor' command runs my entire E2E directory as expected. Tests that I have disabled are reported as skipped.
However, I'm using gulp-protractor to handle E2E now. But when I run gulp protractor, the disabled tests are reported as failed.
I can't seem to figure out what the problem is.
This is the code that is controlling my gulp e2e tasks.
'use strict';
var
gulp = require('gulp'),
load = require('gulp-load-plugins')(),
browserSync = require('browser-sync'),
paths = gulp.paths;
//starts protractor
function runProtractor(done) {
gulp.src(paths.e2e + '/**/**/*.js')
.pipe(load.protractor.protractor(
{
configFile: 'protractor.conf.js'
}
))
.on('error', function (e) {
// Make sure failed tests cause gulp to exit non-zero
throw e;
})
.on('end', function () {
// Close browser sync server
browserSync.exit();
done();
});
}
//starts local, selenium, and then starts protractor
gulp.task('protractor:src', ['serve:e2e', 'webdriver-update'], runProtractor);
// Downloads the selenium webdriver
gulp.task('webdriver-update', load.protractor.webdriver_update);
Turns out my gulp task dependencies weren't being processed sequentially, which is what was needed.
This was helpful: http://schickling.me/synchronous-tasks-gulp/
Short of it: started using Gulp recently (convert from Grunt), and am trying to use both Gulp's default watch task (not gulp-watch from npm) for SASS/JS/HTML and gulp-nodemon (from npm) to restart an Express server upon changes. When running just gulp watch, it works fine; and when running gulp server (for nodemon) that works fine. However, using both together (shown below in the configuration of the default task), the watch stuff isn't working. The task is running, and on the CLI gulp shows 'Starting' and 'Finished' for the watch tasks, but the files don't update.
Relevant task configurations:
Concat javascript:
gulp.task('js:app', function(){
return gulp.src([
pathSource('js/application/modules/**/*.js'),
pathSource('js/application/_main.js')
])
.pipe(concat('application.js'))
.pipe(gulp.dest('./build/assets/js')).on('error', utils.log);
});
Nodemon, restart on changes to express app:
gulp.task('express', function(){
return nodemon({script:'server.js', ext:'js', cwd: __dirname + '/express', legacyWatch: true})
.on('restart', function(){
//gulp.run('watch'); // doesn't work :(
});
});
Watch javascript changes, and run js:app for concat'ing.
gulp.task('watch', function(){
gulp.watch(pathSource('js/application/**/*.js'), ['js:app']);
});
Default task, to initialize gulp watch and nodemon simultaneously:
gulp.task('default', ['watch', 'express']);
If anyone has any ideas, thanks in advance!
gulp.run calls have been deprecated, so I'd try a different approach. Since you're already using gulp, may I suggest giving gulp-nodemon a try?
As per gulp-nodemon documentation, you can pass it an array of tasks to execute:
UPDATE: Here's the full gulpfile.js file, together with a working sample on github.
'use strict';
// Main dependencies and plugins
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var nodemon = require('gulp-nodemon');
var assets = 'assets/js/**/*.js';
var publicDir = 'public/javascripts';
// Lint Task
gulp.task('lint', function () {
return gulp.src(assets)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
// Concatenate and minify all JS files
gulp.task('scripts', function () {
return gulp.src(assets)
.pipe(concat('global.js'))
.pipe(gulp.dest(publicDir))
.pipe(rename('global.min.js'))
.pipe(uglify())
.pipe(gulp.dest(publicDir));
});
// Watch Files For Changes
gulp.task('watch', function () {
gulp.watch(assets, ['lint', 'scripts']);
});
gulp.task('demon', function () {
nodemon({
script: 'server.js',
ext: 'js',
env: {
'NODE_ENV': 'development'
}
})
.on('start', ['watch'])
.on('change', ['watch'])
.on('restart', function () {
console.log('restarted!');
});
});
// Default Task
gulp.task('default', ['demon']);
This way, you spawn the watch task upon nodemon's start and ensure that the watch task is again triggered whenever nodemon restarts your app.
EDIT: seems you should be calling the on-change event from gulp-nodemon, which will handle compile tasks before the restart event triggers.
EDIT: It seems nodemon's on('change', callback) is removed from their API
FWIW, it seems that using the cwd parameter on gulp-nodemon's configuration actually sets the entire gulp cwd to that directory. This means future tasks will be executed in the wrong directory.
I had this problem when running gulp watch tasks on my frontend server at the same time as nodemon tasks on my backend server (in the same gulpfile), there was a race condition wherein if the nodemon command was executed first, the frontend stuff would actually build into (Home)/backend/frontend instead of (Home)/frontend, and everything would go pearshaped from there.
I found that using watch and script params on gulp-nodemon worked around this (although it still looks like nodemon is watching my entire project for changes rather than the built backend directory).
I have a very minimal gulpfile as follows, with a watch task registered:
var gulp = require("gulp");
var jshint = require("gulp-jshint");
gulp.task("lint", function() {
gulp.src("app/assets/**/*.js")
.pipe(jshint())
.pipe(jshint.reporter("default"));
});
gulp.task('watch', function() {
gulp.watch("app/assets/**/*.js", ["lint"]);
});
I cannot get the watch task to run continuously. As soon as I run gulp watch, it terminates immediately.
I've cleared my npm cache, reinstalled dependencies etc, but no dice.
$ gulp watch
[gulp] Using gulpfile gulpfile.js
[gulp] Starting 'watch'...
[gulp] Finished 'watch' after 23 ms
It's not exiting, per se, it's running the task synchronously.
You need to return the stream from the lint task, otherwise gulp doesn't know when that task has completed.
gulp.task("lint", function() {
return gulp.src("./src/*.js")
^^^^^^
.pipe(jshint())
.pipe(jshint.reporter("default"));
});
Also, you might not want to use gulp.watch and a task for this sort of watch. It probably makes more sense to use the gulp-watch plugin so you can only process changed files, sort of like this:
var watch = require('gulp-watch');
gulp.task('watch', function() {
watch({glob: "app/assets/**/*.js"})
.pipe(jshint())
.pipe(jshint.reporter("default"));
});
This task will not only lint when a file changes, but also any new files that are added will be linted as well.
To add to OverZealous' answer which is correct.
gulp.watch now allows you to pass a string array as the callback so you can have two separate tasks. For example, hint:watch and 'hint'.
You can then do something like the following.
gulp.task('hint', function(event){
return gulp.src(sources.hint)
.pipe(plumber())
.pipe(hint())
.pipe(jshint.reporter("default"));
})
gulp.task('hint:watch', function(event) {
gulp.watch(sources.hint, ['hint']);
})
This is only an example though and ideally you'd define this to run on say a concatted dist file.