Upgrade Gulp 3 to Gulp 4 - gulp.start.apply - gulp

I have an existing launch.js and gulpfile.js created for Node6/Gulp3 which I need to upgrade to Node14/Gulp4.
Can anyone please guide if I have upgraded call to gulp.start.apply correctly -
Existing snippet from launch.js in Gulp3 -
var tasks = argv._;
var toRun = tasks.length ? tasks : ['default'];
...
require("./gulpfile.js");
...
var gulpInst = require("gulp");
gulpInst.start.apply(gulpInst, toRun);
I have tried changing last line of code to following - but I am not able to run the task -
gulpInst.task('default', gulpInst.series(toRun[0], function(done) { done(); }));
'dev' and 'prod' are two tasks defined in gulpfile.js. So, I am calling launch.js from command prompt as -
node launch.js dev
but no task is run :(
Have I updated gulp.start.apply with correct code for Gulp4?
Thanks a lot!

Just in case if someone else looking for answer -
Here is how I was able to run the task in Gulp 4 -
gulpInst.task(toRun)();
where 'toRun' is the task that needs to be run.
HTH.

Related

gulp polymer-build not generating expected bundle?

I have the following gulp task (please see below), which I'm trying to run to automate the polymer build. However, all I'm seeing in the resulting /build folder is an index.html. No dependencies, and I was under the impression that the resulting file would be called shared-bundle.html. Also, it's not fetching any of my bower dependencies:
const PolymerProject = require('polymer-build').PolymerProject;
const project = new PolymerProject(require('./polymer.json'));
gulp.task('build', () => {
mergeStream(project.sources(), project.dependencies())
.pipe(project.bundler())
.pipe(gulp.dest('./build/'));
});
This is the documentation I was referencing: https://www.npmjs.com/package/polymer-build
Any ideas what I might be missing?
Apparently I was just missing the entrypoint param here:
const project = new PolymerProject({entrypoint: 'my-page.html'});

Polymer: two gulp errors at build time: 'async completion' and 'apply' property

I'm trying to run gulp to build my app like Rob Dodson explains here.
Original error
At the command line, if I run:
npm run build
I get the following error:
[20:50:55] Using gulpfile ~/path/to/gulpfile.js
[20:50:55] Starting 'default'...
Deleting build/ directory...
[20:50:56] The following tasks did not complete: default
[20:50:56] Did you forget to signal async completion?
It appears there is some task described as "signal async completion?" What does this mean? And how do I do it?
Alternate error
However if I run the following at the command line:
gulp
I get a different error message as follows:
[23:40:57] Using gulpfile ~/path/to/gulpfile.js
/usr/local/lib/node_modules/gulp/bin/gulp.js:129
gulpInst.start.apply(gulpInst, toRun);
^
TypeError: Cannot read property 'apply' of undefined
at /usr/local/lib/node_modules/gulp/bin/gulp.js:129:19
at nextTickCallbackWith0Args (node.js:420:9)
at process._tickCallback (node.js:349:13)
at Function.Module.runMain (module.js:443:11)
at startup (node.js:139:18)
at node.js:968:3
Why would there be different error messages? Does that give a hint what's actually causing the errors? If so, what is it? And what can I do to fix it?
My code
I just copied the files package.json, polymer.json and gulpfile.js from the sample code Rob supplied here. Then I ran npm install as this answer describes.
gulpfile.js
'use strict';
// Documentation on what goes into PolymerProject.
const path = require('path');
const gulp = require('gulp');
const mergeStream = require('merge-stream');
const del = require('del');
const polymerJsonPath = path.join(process.cwd(), 'polymer.json');
const polymerJSON = require(polymerJsonPath);
const polymer = require('polymer-build');
const polymerProject = new polymer.PolymerProject(polymerJSON);
const buildDirectory = 'build/bundled';
/**
* Waits for the given ReadableStream
*/
function waitFor(stream) {
return new Promise((resolve, reject) => {
stream.on('end', resolve);
stream.on('error', reject);
});
}
function build() {
return new Promise((resolve, reject) => {
// Okay, so first thing we do is clear the build
console.log(`Deleting build/ directory...`);
del([buildDirectory])
.then(_ => {
// Okay, now lets get your source files
let sourcesStream = polymerProject.sources()
// Oh, well do you want to minify stuff? Go for it!
// Here's how splitHtml & gulpif work
.pipe(polymerProject.splitHtml())
.pipe(gulpif(/\.js$/, uglify()))
.pipe(gulpif(/\.css$/, cssSlam()))
.pipe(gulpif(/\.html$/, htmlMinifier()))
.pipe(polymerProject.rejoinHtml());
// Okay now lets do the same to your dependencies
let depsStream = polymerProject.dependencies()
.pipe(polymerProject.splitHtml())
.pipe(gulpif(/\.js$/, uglify()))
.pipe(gulpif(/\.css$/, cssSlam()))
.pipe(gulpif(/\.html$/, htmlMinifier()))
.pipe(polymerProject.rejoinHtml());
// Okay, now lets merge them into a single build stream.
let buildStream = mergeStream(sourcesStream, depsStream)
.once('data', () => {
console.log('Analyzing build dependencies...');
});
// If you want bundling, do some bundling! Explain why?
buildStream = buildStream.pipe(polymerProject.bundler);
// If you want to add prefetch links, do it! Explain why?
// buildStream = buildStream.pipe(new PrefetchTransform(polymerProject));
// Okay, time to pipe to the build directory
buildStream = buildStream.pipe(gulp.dest(buildDirectory));
// waitFor the buildStream to complete
return waitFor(buildStream);
})
.then(_ => {
// You did it!
console.log('Build complete!');
resolve();
});
});
}
gulp.task('default', build);
The original error is unrelated to the "alternate error".
While the build task runs gulp, npm run prioritizes the locally-installed gulp (at node_modules/.bin/gulp) before the system-installed gulp. Running gulp yourself (without npm run) would invoke the globally-installed gulp, which may result in an error if it's incompatible with your project (e.g., Gulp 3 binary with Gulp 4 API in your scripts, which appears to be the case). You could either install Gulp 4 so that you can run gulp yourself, or continue using npm run build.
To troubleshoot the original error, I recommend starting from the Polycast's original source (if you haven't already) to determine what the difference could be.
If you prefer to stick with your current track, I suggest a few things:
Verify the paths in your HTML imports, as a path to a non-existent file would cause a silent error (polymer-build issue 88). It might be helpful to run polymer build -v (verbose build).
Add buildStream.on('error', (err) => console.log(err)) after let buildStream = ... in case any unsuppressed error events crop up in that stream.
I recommend you use the new version of PSK Custom Build:
https://github.com/PolymerElements/generator-polymer-init-custom-build/
It has the gulpfile.js updated.
The problem was caused by an incorrect import path.
incorrect path
<link rel="import" href="../../../bower_components/polymer/polymer.html">
correct path
<link rel="import" href="../../bower_components/polymer/polymer.html">
As #tony19, correctly described, that errant import path caused a silent failure.
I found this by pursuing the path suggested by #abdonrd. I followed the instructions here as follows.
First, I copied my project. Then I loaded into the my-app directory per the below described procedure.
https://github.com/PolymerElements/generator-polymer-init-custom-build/
npm install -g polymer-cli
npm install -g generator-polymer-init-custom-build
mkdir my-app
cd my-app
polymer init custom-build
polymer build -v # the results of this command highlighted my error in red
The error showed the path of the missing file. Which I noticed was located one level higher than it should have been because the root directory my-app/ was missing from the path. Then I had to search manually through all the files using the search string polymer/polymer.html until I found a mismatch between the number of ../ in the import path (3 in this case) and the number of folders deep into the root directory the importing file was (2 in this case).
After I corrected the file path, I again ran:
polymer build -v # building the project again, correctly this time
polymer serve build/bundled # to test serve the build/bundled version

Gulp clean not working when in an array of tasks

I am using yii2 to build a web service. And to help me to put together all the things I use gulp. I have a file structure similar to this
gulpfile.js
index.php
basics/
-composer.json
-vendor/
after you get all the dependencies using composer they save into vendor folder. The problem is that for some reason yii2 saves bower asset in a folder called bower-asset, but it will only work if the folder is called bower. So I wrote these two tasks to help me with this. task one copies the content of bower-asset folder into bower folder in the same directory and the second task deletes bower-asset folder. My problem occurs when task two is ran from default task. Then it returns an error like this
[15:11:20] Starting 'bower-del'...
events.js:85
throw er; // Unhandled 'error' event
^
Error: ENOENT, lstat '/Users/Me/Documents/mamp/dumb/game/basic/vendor/bower-asset/jquery/dist'
at Error (native)
It also appears if I try to tell task to to wait for task one to be finished before task two starts like
gulp.task('bower-del', ['bower-copy'], function () {
The thing that surprises me the most is that if I run task two by itself ie gulp bower-del it deletes the folder no problem.
I have taken other tasks from my gulp file for simplicity purposes.
This is what my gulp tasks look like:
// Copies bower-asset into bower folder
gulp.task('bower-copy', function(){
gulp.src('./basic/vendor/bower-asset/**/*')
.pipe(gulp.dest('basic/vendor/bower/'));
});
// Deletes old bower-asset folder
gulp.task('bower-del', function () {
return gulp.src('./basic/vendor/bower-asset/', {read: false})
.pipe(clean());
});
gulp.task('default', ['bower-copy', 'bower-del']);
You should run de bower-del in sequence. In my SkeletonSpa I have the same issue with cleaning before a build. Here I have 2 tasks clean and build, where the build task should only run when the clean task is finished, eg. they should not run in parallel.
My implementation is as follows:
gulp.task('build', (cb) => {
let runSequence = require('run-sequence');
runSequence('clean', ['info', 'styles', 'scripts', 'images', 'copy'], 'todo', cb);
});
gulp.task('clean', ['clear-cache'], () => {
let del = require('del');
let vinylPaths = require('vinyl-paths');
return gulp.src([settings.dist, settings.reports])
.pipe(vinylPaths(del));
});
This will do the trick. Just take a look at the run-sequence plugin and implement it ;-)

Cannot read property 'emit' of undefined in gulp-browserify

i am running into a problem. I have created my own seed: https://github.com/damirkusar/leptir-angular-seed with gulp, browserify and more.
Everything worked fine, since i had the good idea to update node from 10.32 to 12.5, i am getting the below error. I think that this is since then. I tried it also on a different machine, same setup, same error.
so, after npm install and bower install i am starting the app with:
gulp
or when trying to build the project with
gulp build
i am getting this error:
leptir-angular-seed/node_modules/gulp-browserify/node_modules/browserify/node_modules/module-deps/index.js:162
rs.on('error', function (err) { tr.emit('error', err) });
^
TypeError: Cannot read property 'emit' of undefined
at ReadStream.<anonymous> (/leptir-angular-seed/node_modules/gulp-browserify/node_modules/browserify/node_modules/module-deps/index.js:162:39)
at ReadStream.emit (events.js:107:17)
at fs.js:1618:12
at FSReqWrap.oncomplete (fs.js:95:15)
Here is also the link to the package.json: https://github.com/damirkusar/leptir-angular-seed/blob/450ffe99943036cd5a670e54ec3884c02bd7bb8a/package.json.
but luckily, karma start executes the tests and all tests are passing..
Maybe some versions are not really supported correctly?
Does anybody have an idea what causes this problem?
-- edit 2015-June-25 14:23
I am using the module which cause the problem in my gulp file like this:
// Browserify task
gulp.task('browserify', function () {
gulp.src(paths.browserify[0])
.pipe(browserify({
insertGlobals: true,
debug: true
}))
// Bundle to a single file
.pipe(concat('bower.js'))
// Output it to our dist folder
.pipe(gulp.dest(paths.destination_public))
.pipe(refresh(lrServer)); // Tell the lrServer to refresh;
gulp.src(paths.browserify[1])
.pipe(browserify({
insertGlobals: true,
debug: true
}))
// Bundle to a single file
.pipe(concat('app.js'))
// Output it to our dist folder
.pipe(gulp.dest(paths.destination_public))
.pipe(refresh(lrServer)); // Tell the lrServer to refresh;
});
which browserifyies these app.js file and its content:
require('./modules/core');
require('./modules/core');
and bower.js with its content:
'use strict';
require('jquery');
require('bootstrap');
require('moment');
require('underscore');
require('angular');
require('angular-animate');
require('angular-bootstrap');
require('angular-bootstrap-tpls');
require('angular-cookies');
require('angular-mocks');
require('angular-resource');
require('angular-ui-router');
require('angular-ui-utils');
require('angular-translate');
require('angular-translate-loader-static-files');
require('angular-translate-loader-url');
require('angular-translate-storage-cookie');
require('angular-translate-storage-local');
thank you so much
"...but in fact, otherwise i am not using this module which causes the error." - damir
modules has dependencies too. it seems to be a problem with one of these modules that are used by an other module.
It could be possible that a module you are using has a dependency on a node component of the old version. Try to get the old back until the bug is fixed.
On a windows machine (instead of mine mac) it showed me a better error message.
I referenced bower packages which where not installed.. but totally forgot to remove it from package.json and bower.js.
so i removed code in the above files which referenced the following packages:
angular-translate-storage-cookie
angular-translate-storage-local
-- UPDATE 27th June 2015 - 22:41 --
I saw that gulp-browserify is blacklisted by gulpjs, so i thought its better to get rid of it, because i faced also problems on windows machines. Instead of using gulp-browserify, i am using plain browserify with vinyl-transform.
First, update your package.json with this:
"browserify": "9.0.4",
"vinyl-transform": "1.0.0"
You see, that i am using exactly these two versions, this is because with newer browserify versions, things are not really working, so to be sure that it works also when i update my packages, i keep them in this versions.
Then lets update our gulp file. We will need to add these two lines:
var browserify = require('browserify'),
transform = require('vinyl-transform');
and my new task looks like this:
gulp.task('browserify', function () {
var browserified = transform(function(filename) {
var b = browserify(filename);
return b.bundle();
});
return gulp.src(paths.browserify)
.pipe(browserified)
.pipe(gulp.dest(paths.destination_public));
});
its now shorter and much cleaner. My paths are configured like this..
var paths = {
...
browserify: ['./public/bower.js', './public/app.js'],
...
destination_public: './dist/'
};
now my seed is working on mac and windows the same way.
https://github.com/damirkusar/leptir-angular-seed

Gulp does not work when returning stream

The following Gulp setup does not work:
var templateCache = require("gulp-angular-templatecache");
var less = require("gulp-less");
gulp.task("angular-templates", function(){
return gulp.src(TEMPLATES_SOURCES)
.pipe(templateCache(TEMPLATES_JS, {module: "moonwalk", root: TEMPLATES_ROOT}))
.pipe(gulp.dest("Temp/"));
});
gulp.task("less-compile",function(){
return gulp.src("**/*.less")
.pipe(less())
.pipe(gulp.dest("./"));
});
gulp.task("release-assets", ["angular-templates", "less-compile"], function() {
return gulp.src("./Content/**/*.cshtml")
.pipe(gulp.dest("Dist/"));
});
When I run gulp release-assets the output is the following:
[01:24:06] Starting 'angular-templates'...
[01:24:06] Starting 'less-compile'...
[01:24:06] Finished 'angular-templates' after 605 ms
... not good ...
However if I change the second task by removing the return like this:
gulp.task("less-compile",function(){
gulp.src("**/*.less")
.pipe(less())
.pipe(gulp.dest("./"));
});
Then the setup does work!? The output of gulp release-assets then is:
[01:21:54] Starting 'angular-templates'...
[01:21:54] Starting 'less-compile'...
[01:21:54] Finished 'less-compile' after 2.89 ms
[01:21:54] Finished 'angular-templates' after 741 ms
[01:21:54] Starting 'release-assets'...
[01:22:03] Finished 'release-assets' after 8.9 s
I do not understand that problem. I thought it was mandatory to return the stream that is provided by gulp.src()?
Can somebody explain, why the above setup is not working if I return on gulp.src()?
So the main points raised in the comments; return doesn't seem like it is throwing off gulp; you are using the latest version of gulp-less, and your tasks look OK from a syntax standpoint.
The main takeaway from this is that project structure is quite important, so that when you specify a glob such as **/*.less you have to be aware of what files it can match; in this case the glob is far too greedy and will match things in node_modules that may or may not be relevant to your project. Because gulp.src is an expensive operation, it is a good practice to organise your source files into directories and limit glob's scope to be within those directories.
A better glob pattern would be something along the lines of ./lib/styles/**/*.less - that way you have both scoped the glob appropriately and you also keep your less files in one place. Your gulp task should therefore look something like the following:
gulp.task("less-compile", function () {
return gulp.src("./lib/styles/**/*.less")
.pipe(less())
.pipe(gulp.dest("./dist/css"));
});
I had a similar problem, and solved it by changing the installed gulp version from 3.8.7 to 3.8.5 in package.json:
"devDependencies": {
"gulp": "3.8.5"
}
Must be a change or error in the newer version preventing the pipe(gulp.src('.')) from resolving the return statement.