gulp 4 dependencies and plugins - angularjs

Due to issues with gulp 3 forcing my tasks to run concurrently, I have starting investigating gulp 4 with the hope of exploiting its gulp.series and gulp.parallel functions but I have hit a wall.
After some research I came across the undertaker-forward-reference plugin that should allow me to have something like:
var gulp = require('gulp');
var FwdRef = require('undertaker-forward-reference');
gulp.registry(FwdRef());
gulp.task('biggie', gulp.series('smalls'));
gulp.task('smalls', function(cb){
console.log("This is awesome");
cb();
});
where task 'biggie' depends on task 'smalls' but smalls is defined lower in in the gulp file. I get the following error:
assert.js:86
throw new assert.AssertionError({
^
AssertionError: Task never defined: smalls
What am I getting wrong here....
P.S. I am new to this so please be kind.

You just need to define "smalls" first. like...
var gulp = require('gulp');
var FwdRef = require('undertaker-forward-reference');
gulp.registry(FwdRef());
gulp.task('smalls', function(cb){
console.log("This is awesome");
cb();
});
gulp.task('biggie', gulp.series('smalls'));

Related

Angular translate - When multiple loader it execute only the last one

I've got a project using angular translate with a custom loader.
Basically, this is the config in my provider (which is working perfectly).
Provider (stuff executed in the config of my app)
$translateProvider.useSanitizeValueStrategy('sanitize');
$translateProvider.useLoader('componentsTranslationLoader');
$translateProvider.preferredLanguage($language);
As you can see, I use my own componentsTranslationLoader. It does the stuff as expected.
Factory (componentsTranslationLoader)
return function(options) {
var deferred = $q.defer();
var translations = {};
$http.get('languages/components/' + options.key + '.json').success(function(keys) {
translations = keys;
deferred.resolve(translations);
});
return deferred.promise;
};
Everythings is fine from here.
I have to use a library in this project (company's one, I can edit it), and this library also has his own angular translate stuff (basically the same thing).
It has a custom loader, initialized into the config.
When my project is executed, I expect that both loader do their stuff and extend the language with their keys.
It didn't.
Only the last loader is executed (see it with logs).
So, how can I resolve this conflict properly please ?
Is there something wrong with my way of using angular translate ?
Thanks for the help guys.
Edit (more informations added)
I added more call like this one into the config with different 'fake' loader:
$translateProvider.useLoader('aFakeLoaderWithLogs');
And the problem still the same, only the last one into the config is called.
I searched for topics with similar issues and found nothing, even in the documentation.
Try this approach of merging responses. Works for me very well.
function customLoader($http, $q, localeUrl, errorCodeUrl) {
return function (options) {
var deferred = $q.defer();
var translations = [];
$q.all([
$http.get(localeUrl + "locale-" + options.key +".json"),
$http.get(errorCodeUrl + "?lang=cs")
]).then(function(response, status) {
translations.push(response[0].data);
translations.push(response[1].data);
console.log(translations);
deferred.resolve(translations);
return translations;
});
return deferred.promise;
};
}

Gulp Task Breaking on Angular Files

I have the gulp task set up and running to create an Angular app, and it runs without error and creates the files correctly, but when I load the page on a browser, I get following error messages.
Is there some step or some plugin I'm missing to get the Angular files to all "work"? I've used the angularFilesort() and ngAnnotate() plugins already.
var bower = gulp.src(bower_files)
.pipe(concat("bower-expanded.js"))
.pipe(gulp.dest(paths.prod))
.pipe(rename("bower.js"))
.pipe(uglify())
.pipe(gulp.dest(paths.prod + paths.js));
// gather and compress the app's js files
var app = gulp.src(paths.source + "app/**/*.js")
.pipe(angularFilesort())
.pipe(concat("app-expanded.js"))
.pipe(ngAnnotate({
add: true,
single_quotes: true
}))
.pipe(gulp.dest(paths.prod))
.pipe(rename("app.js"))
.pipe(uglify())
.pipe(gulp.dest(paths.prod + paths.js));
The errors are
TypeError: (intermediate value)(...) is not a function
(function(angular) {
which points to these lines of code
(function(angular) {
'use strict';
/**
* Called with an array this acts like map, otherwise it acts like _.mapValues
* in lodash.
* #return {Array|Object} The same type as the input argument.
*/
var mapValues = function(obj, callback) {
if (angular.isArray(obj))
The other error is
Error: [$injector:modulerr] Failed to instantiate module app due to:
[$injector:modulerr] Failed to instantiate module angularSpinner due to:
[$injector:nomod] Module 'angularSpinner' is not available!
You either misspelled the module name or forgot to load it.
If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.4/$injector/nomod?p0=angularSpinner
I notice you're not running ngAnnotate on your bower components, but you are running uglify on them. This could be causing your problem.
Try:
var bower = gulp.src(bower_files)
.pipe(concat("bower-expanded.js"))
.pipe(ngAnnotate({
add: true,
single_quotes: true
}))
.pipe(gulp.dest(paths.prod))
.pipe(rename("bower.js"))
.pipe(uglify())
.pipe(gulp.dest(paths.prod + paths.js));
As an aside, it's not an awesome idea to concatenate all of your dependencies into a single file. The browser can handle asynchronously loading multiple JS files and will do so much faster than loading a single, massive JS file.
After reading through various answers in SO the first error usually refers to a forgotten ; in the lines prior to the error.
You can configure the concat task to use ; as a seperator for js files to avoid this.
On the second I agree with #ShaunScovil, also using the .min files provided from each bower package is safer.
You can make use of this main-bower-files package to set this up depending of the env and automate the process of building one or more files of all bower dependencies.
This same thing happens with GruntJS and I recently learned how to fix it. Make sure all of your angular js controllers, directive and filters have proper includes on them.
Example wont work:
angular.module('uniApp').directive('autoFocus', function ($timeout) {
return function (scope, element, attrs) {
scope.$watch(attrs.autoFocus,
function (newValue) {
$timeout(function () {
element.focus();
});
}, true);
};
});
Notice on the above how the $timeout is not properly included?
Example will work:
angular.module('uniApp').directive('autoFocus',['$timeout', function ($timeout) {
return function (scope, element, attrs) {
scope.$watch(attrs.autoFocus,
function (newValue) {
$timeout(function () {
element.focus();
});
}, true);
};
}]);
Now the $timeout is properly included. Make sure to check this little detail on all controllers, filters, and directives.

Wanting To Optionally Add JavaScript code using Gulp

I've got a gulpfile.js that bundles using browserify and I want to be able to optionally add one line to one of my javascript files based on a variable like useMock. Below is my GulpFile.js build step
function bundle (bundler) {
return bundler
.bundle()
.pipe(source('app.js'))
.pipe(gulp.dest('./dist'))
.pipe(browserSync.stream());
}
The last line of the file below is the one I want to optionally include.
module.exports = require('angular')
.module('AngularUApp', [
require('angular-ui-router'),
require('angular-sanitize'),
require('../../base'),
require('./home'),
require('./speaker'),
require('./author')
])
.config(enableHtml5Mode)
.name;
enableHtml5Mode.$inject = ['$locationProvider'];
function enableHtml5Mode($locationProvider) {
console.log('enableHtml5Mode');
$locationProvider.html5Mode(true);
}
// I want to optionally include this from my gulpfile.js
require('../mock');
I want to be able to have a production and dev build where the dev includes the extra line and production does not. If there is a better more recommended way to do this, please suggest.
I found the answer myself. Using the browserify api itself from this link:
https://github.com/substack/node-browserify#usage
var combinedArgs = merge(watchify.args, { debug: true });
var b = browserify(baseDir,combinedArgs);
b.add('angu/mock');
var watcher = watchify(b);
I had a problem earlier because I forgot the relative directory from gulp is different than from inside the JavaScript itself.

Terminate gulp-watch task

I want my gulp watch task to run only once, then stop watching. Now, if I run 'gulp' from the command line, the watch tasks keeps the gulp task running. I have to hit Ctrl-C to stop it.
when you run gulp watch, it will keep watching for file changes until you cancel it with CTRL-C. I you do not want this, then you can make a separate gulp task to do your building.
You would have 2 tasks then: gulp watch and gulp build. As the build wouldn't run the watch task, it will stop when finished.
Please take a look at a GitHub project of mine where I do things like this: skeletonSPA on GitHub.
If you take a look at the gulpfile.js, you see that the default task will execute the build task.
The build task on its turn will execute info, clean, styles, scripts, images, copy, todo; leaving you with a full build and working frontend.
After running these tasks, it will stop and gives you focus to the command line.
Here's a very basic example GulpFile.js:
var gulp = require('gulp'),
watch = require('gulp-watch'),
runSequence = require('gulp-sequence'),
webpack = require('webpack-stream');
gulp.task('webpack', function() {
return gulp.src('client/index.js')
.pipe(webpack({
output: {
filename: 'dist/bundle.js'
},
devtool: 'source-map'
}))
.pipe(gulp.dest('.'));
});
// other tasks
gulp.task('build', ['webpack', 'other tasks... ']);
gulp.task('watch', function(callback) {
gulp.watch('./client/**/*.js', {}, ['webpack']);
// more watches if required
});
gulp.task('default', function(callback) {
runSequence('build', 'watch', callback);
});
$ gulp build > will just run build the once and then exit.
$ gulp watch > will start watching (ctrl-c to exit).
$ gulp > will execute build and after that's complete it will run watch (ctrl-c to exit).
Note: I'm using the gulp-sequence plug to ensure that when running $ gulp the build will complete before the watch begins.
gulp.watch returns a FSWatcher object, which has a .close() method you can call to cancel the watch task:
var watchStream = gulp.watch(
src,
{ignoreInitial: true},
myGulpTask)
.on("change", function (triggerFileName) {
watchStream.close();
});
ignoreInitial = true prevents the task from running when the watcher starts. watchStream.close() will cancel the watcher, but the task will run once. So all in all, you get one task run.
This is with Gulp 4.

Using chance.js inside AngularJS end to end tests

I'm trying to generate some random data for my e2e tests. Seems that the only library I found was chance.js. But can't make it works. This is what I've tried so far:
describe('In the login page', function () {
var chance = new Chance(); // ReferenceError: Chance is not defined
}
Then adding
beforeEach(function(){
browser.executeScript(
function() {
return chance;
}).then(function(_chance){
chance = _chance; //It returns an object, but can't use any of the methods.
});
});
But if I try
beforeEach(function(){
browser.executeScript(
function() {
return chance.email(); //Note this line here
}).then(function(_chance){
chance = _chance; //It returns an email
});
});
Thats all I have so far... any clue/idea?
First, install chance.js in your project:
npm install chance --save-dev
This installs chance.js as a node module in your project. Then include it in your spec and instantiate:
var chance = require('../node_modules/chance').Chance();
Then call in your spec. For example:
it('should add a new friend', function() {
var friendName = chance.string()
friendPage.addFriend(friendName);
expect(friendPage.inResults(friendName)).toBeTruthy();
});
Hope that helps...
Okay first you need to download chance.js and add that file to your html directory
Second add script src="chance.js" in a proper script tag your section
Within another script tag you should be able to use any of the functions that are listed on the website
working jsfiddle: http://jsfiddle.net/c96x2cpa/
fiddle js code:
alert(chance.bool());
alert(chance.character());
alert(chance.floating());
It was easy at the end :)
You just need to install chance as a node module.
npm install chance
Then require the node in the spec
// Load Chance
var Chance = require('chance');
And use it where ever you want
chance.email()
Enjoy!

Resources