Use Gulp to wrap javascript files with a IIFE - angularjs

I have an angular app that has a lot of .js files.
It's boring to add an IIFE to each file and then add 'use strict'.
Is there any way to automate this? I use gulp to run tasks.

Use the gulp-wrap plugin with a simple template:
var wrap = require("gulp-wrap");
gulp.src("./src/*.js")
.pipe(wrap('(function(){\n"use strict";\n<%= contents %>\n})();'))
.pipe(gulp.dest("./dist"));
This will wrap each file's contents with the template:
(function(){
"use strict";
//contents hereā€¦
})();
You can also store the template on the filesystem, rather than embedding it in your gulpfile, and call gulp-wrap using wrap({src: 'path/to/template'})

Related

minifying js file containing routing

I am minifying an angular project through gulp.This project contains index.html,css,libraries,app.js(Angular module containing routing layer+controllers) and views.
I could easily minify+concat all js files,libraries and css files into one bundle file.HTML files were also easily minified but the problem is i have routing in my app.js which render templateUrl like
.state('dashboard.home', {
url: '/home',
templateUrl: 'app/views/dashboard/home.html'
})
Now,beacause of this routing i cannot minify+concat all html files into one.because each route renders one view with its file name while there will be only one file named bundle.html.
Here,I need a guideline about how to handle this situation.
Thanks Regards
I use the gulp-ng-template for this:
gulpfile.js:
var ngTemplate = require('gulp-ng-template');
....
gulp.task('templates', function () {
return gulp.src(['view1.html', 'view2.html'])
.pipe(ngTemplate({filePath: 'js/tpl.js'}))
.pipe(gulp.dest('test'));
});
ngTemplate combines your views and puts them into the single file js/tpl.js that will look like this:
angular.module('ngTemplates').run(['$templateCache', function($templateCache) {
$templateCache.put('view1.html', '<div class="test">A</div>\n');
$templateCache.put('view2.html', '<div class="test">\n <span>B</span>\n</div>\n');
}]);
Now all you need is to include this file into your index.html. Your views will be available to the angular compiler at their original paths. You don't need to include your original html views into project any more.
You can add this file js/tpl.js to your index.html manually or by using ng-html-replace.
Instead of concatenating all templates into one html file you should use $templateCache angular provider and convert all of your html templates into JavaScript code. By using templateCache you can put all of your teplates into one file and it will work perfectly with routing mechanism. Try this gulp module Gulp ng templates

Managing custom directives

I need to make some custom directives. Every tutorial shows building the directive relative to the controller where it is to be used. I'm sure this is not the right way if you need to put it into another controller.
I have a global controller. Should I put my directives there? I also have a Utilities factory and inject this into my controllers(this keeps everything tidy and manageable). Do directives work the same way?
How do you manage multiple directives and where do you put them?
Add your directives in separate file like directives.js and use those directives in many views or controllers.
directive.js should be included after your app.js
For example if your app.js is like:
var app = angular.module('myangularapp', ['ngResource']);
then your directive.js should be like:
app.directive('confirm', function(ConfirmService) {
});
app.directive('alert', function(AlertService) {
});

Typescript directive html template in gulp

I am looking at switching from Grunt to Gulp and I have everything I need working except for one thing.
When I was using Grunt, I used grunt-ts and it had a very nice feature for dealing with html templates for angular directives. https://www.npmjs.com/package/grunt-ts#html
It takes my directive template html file and creates a .ts file for it. This fits very nicely into our build process since all .ts-files are compiled and concat:ed to one file.
Now, when I use gulp-typescript(https://www.npmjs.com/package/gulp-typescript) I no longer have this feature.
Is there a way to recreate the functionality from grunt-ts to the Gulp workflow?
Basically, what I need to do is:
Watch all *.tpl.html files in a specified directory. [No problem]
When file is changed, minify the html contents (using gulp-minify-html) in the file and add the minified html content to a new file(in the same directory) with this file content:
module [directivename].tpl{
export var html ='MINIFIEDHTML';
}
Any suggestions on how I can accomplish this? Or is there a better way to do this?
`
I believe gulp-angular-templatecache is what you need.
var templateCache = require('gulp-angular-templatecache');
gulp.task('default', function () {
return gulp.src('templates/**/*.html')
.pipe(templateCache())
.pipe(gulp.dest('public'));
});
You can see how John papa does that from here

Can I divide up my app.js file into multiple files in Angular JS?

In my app.js file I have my Angular code like this:
var app = angular
.module('app',
['...'])
.config([
'...',
function (
...) {
}])
.factory('requestInterceptor', function ($q, $rootScope) {
..
return {
..
};
})
Is it possible for me to move the code for the config and the factory out of the file and if so then how do I link this up to the app variable?
I have an app setup this way.
What you can do is declare the module in one file before and separate from everything else. Then just make sure it's the first script file referenced in your HTML.
After that you should be able to just add factories, configs and what not to the app in other files.
Yes. If you define a module, app:
angular.module('app',[]); // Including the [], or list of module dependencies
then you can refer to it later, in other files, by calling module without the second parameter:
angular.module('app').factory('requestInterceptor',...
It is confusing: module is used for both creating a new module, and to add to an existing one, depending on whether you have passed an array as its second parameter.

AngularJS best practices for module declaration?

I have a bunch of Angular modules declared in my app. I originally started declaring them using the "chained" syntax like this:
angular.module('mymodule', [])
.controller('myctrl', ['dep1', function(dep1){ ... }])
.service('myservice', ['dep2', function(dep2){ ... }])
... // more here
But I decided that wasn't very easy to read, so I started declaring them using a module variable like this:
var mod = angular.module('mymodule', []);
mod.controller('myctrl', ['dep1', function(dep1){ ... }]);
mod.service('myservice', ['dep2', function(dep2){ ... }]);
...
The second syntax seems a lot more readable to me, but my only complaint is that this syntax leaves the mod variable out in the global scope. If I ever have some other variable named mod, it would be overridden with this next one (and other issues associated with global variables).
So my question is, is this the best way? Or would it be better to do something like this?:
(function(){
var mod = angular.module('mymod', []);
mod.controller('myctrl', ['dep1', function(dep1){ ... }]);
mod.service('myservice', ['dep2', function(dep2){ ... }]);
...
})();
Or does it even matter enough to care? Just curious to know what the "best practices" are for module declaration.
'Best' way to declare a module
As angular is on the global scope itself and modules are saved to its variable you can access modules via angular.module('mymod'):
// one file
// NOTE: the immediately invoked function expression
// is used to exemplify different files and is not required
(function(){
// declaring the module in one file / anonymous function
// (only pass a second parameter THIS ONE TIME as a redecleration creates bugs
// which are very hard to dedect)
angular.module('mymod', []);
})();
// another file and/or another anonymous function
(function(){
// using the function form of use-strict...
"use strict";
// accessing the module in another.
// this can be done by calling angular.module without the []-brackets
angular.module('mymod')
.controller('myctrl', ['dep1', function(dep1){
//..
}])
// appending another service/controller/filter etc to the same module-call inside the same file
.service('myservice', ['dep2', function(dep2){
//...
}]);
// you can of course use angular.module('mymod') here as well
angular.module('mymod').controller('anothermyctrl', ['dep1', function(dep1){
//..
}])
})();
No other global variables are required.
Of course it depends all on preferences, but I think this is kind of the best practise, as
you don't have to pollute the global scope
you can access your modules everywhere and sort them and their functions into different files at will
you can use the function-form of "use strict";
the loading order of files does not matter as much
Options for sorting your modules and files
This way of declaring and accessing modules makes you very flexible. You can sort modules via function-type (like described in another answer) or via route, e.g.:
/******** sorting by route **********/
angular.module('home')...
angular.module('another-route')...
angular.module('shared')...
How you sort it in the end is a matter of personal taste and the scale and type of the project. I personally like to group all files of a module inside of the same folder (ordered into sub-folders of directives, controllers, services and filters), including all different test-files, as it makes your modules more reusable. Thus in middle-sized projects I end up with a base-module, which includes all basic routes and their controllers, services, directives and more or less complex sub-modules, when I think they could be useful for other projects as well,e.g.:
/******** modularizing feature-sets **********/
/controllers
/directives
/filters
/services
/my-map-sub-module
/my-map-sub-module/controllers
/my-map-sub-module/services
app.js
...
angular.module('app', [
'app.directives',
'app.filters',
'app.controllers',
'app.services',
'myMapSubModule'
]);
angular.module('myMapSubModule',[
'myMapSubModule.controllers',
'myMapSubModule.services',
// only if they are specific to the module
'myMapSubModule.directives',
'myMapSubModule.filters'
]);
For very big projects, I sometimes end up grouping modules by routes, as described above or by some selected main routes or a even a combination of routes and some selected components, but it really depends.
EDIT:
Just because it is related and I ran into that very recently again: Take good care that you create a module only once (by adding a second parameter to the angular.module-function). This will mess up your application and can be very hard to detect.
2015 EDIT on sorting modules:
One and a half year of angular-experience later, I can add that the benefits from using differently named modules within your app are somewhat limited as AMD still does not really work well with Angular and services, directives and filters are globally available inside the angular context anyway (as exemplified here). There is still a semantic and structural benefit though and it might be helpful being able to include/ exclude a module with a single line of code commented in or out.
It also almost never makes much sense to separate sub-modules by type (eg. 'myMapSubModule.controllers') as they usually depend on each other.
I love the angular-styleguide by Johnpapa, and here are some rules that related to this question:
Rule: Named vs Anonymous Functions
Avoid using anonymous functions:
// dashboard.js
angular
.module('app')
.controller('Dashboard', function() { })
Instead, use named functions:
// dashboard.js
angular
.module('app')
.controller('Dashboard', Dashboard);
function Dashboard() { }
As the author says: This produces more readable code, is much easier to debug, and reduces the amount of nested callback code.
Rule : Define 1 component per file.
Avoid multiple components in one file:
angular
.module('app', ['ngRoute'])
.controller('SomeController', SomeController)
.factory('someFactory', someFactory);
function SomeController() { }
function someFactory() { }
Intead, use one file to define the module:
// app.module.js
angular
.module('app', ['ngRoute']);
one file just uses the module to define a component
// someController.js
angular
.module('app')
.controller('SomeController', SomeController);
function SomeController() { }
and another file to define another component
// someFactory.js
angular
.module('app')
.factory('someFactory', someFactory);
function someFactory() { }
Of course, there are many other rules for modules, controllers and services that are quite useful and worth reading.
And thanks to comment of ya_dimon, the above code should be wrapped in IIFE, for example:
(function (window, angular) {
angular.module('app')
.controller('Dashboard', function () { });
})(window, window.angular);
I recently had this conundrum as well. I had started off just like you using the chained syntax, but in the long run it becomes unwieldy with large projects. Normally I'd create a controllers module, a services module and so on in separate files and inject them into my main application module found in another file. For Example:
// My Controllers File
angular.module('my-controllers',[])
.controller('oneCtrl',[...])
.controller('twoCtrl',[...]);
// My Services File
angular.module('my-services',[])
.factory('oneSrc',[...])
.facotry('twoSrc',[...]);
// My Directives File
angular.module('my-directives',[])
.directive('oneDrct',[...])
.directive('twoDrct',[...]);
// My Main Application File
angular.module('my-app',['my-controllers','my-services','my-directives',...]);
But each one of these files was getting way to large as the project grew. So I decided to break them up into separate files based on each controller or service. I found that using angular.module('mod-name'). without the injection array, is what you need for this to work. Declaring a global variable in one file and expecting that to be readily available in another just doesn't work or could have unexpected results.
So in short my application looked something like this:
// Main Controller File
angular.module('my-controllers',[]);
// Controller One File
angular.module('my-controllers').controller('oneCtrl',[...]);
//Controller Two File
angular.module('my-controllers').controller('twoCtrl',[...]);
I did this to the services file as well, no need to change the main application module file you'd still be injecting the same modules into that.
One other practice is to stuff controllers, directives, etc in their own modules and inject those modules into your "main" one:
angular.module('app.controllers', [])
.controller('controller1', ['$scope', function (scope) {
scope.name = "USER!";
}]);
angular.module('app.directives', [])
.directive('myDirective', [function () {
return {
restrict: 'A',
template: '<div>my directive!</div>'
}
}]);
angular.module('app', [
'app.controllers',
'app.directives'
]);
Nothing is left in the global scope.
http://plnkr.co/edit/EtzzPRyxWT1MkhK7KcLo?p=preview
I like to divide my files and my modules.
Something like this:
app.js
var myApp = angular.module('myApp', ['myApp.controllers', 'myApp.directives', 'myApp.services']);
myApp.config(['$routeProvider', function($routeProvider) {
/* routes configs */
$routeProvider.when(/*...*/);
}]);
directives.js
var myDirectives = angular.module('myApp.directives', []);
myDirectives.directive( /* ... */ );
service.js
var myServices = angular.module('myApp.services', []);
myServices.factory( /* ... */ );
Im not a big fan of the "chained style", so I prefer to write down my variable always.
I suggest to follow Angularjs Style Guide.
They handle all concept from naming convention, to modularize your app and so on.
For angular 2, you can check Angular 2 Style Guide
For me, chaining is the most compact way:
angular.module("mod1",["mod1.submod1"])
.value("myValues", {
...
})
.factory("myFactory", function(myValues){
...
})
.controller("MainCtrl", function($scope){
// when using "Ctrl as" syntax
var MC = this;
MC.data = ...;
})
;
That way I can easily move components between modules, never need to declare the same module twice, never need any global variables.
And if the file gets too long, solution is simple - split into two files, each declaring its own module at the top. For more transparency, I try to keep one unique module per file and name it resembling the full path of the file. This way also I never need to write a module without [], which is a common pain point.

Resources