Load external modules (third party libs) in Angularjs - javascript

Until recently I used to develop my js applications with Backbone-js.
Now, I wish to start using Angular-js for the first time.
In my backbone-js apps I used requirejs to load any third party library, it let my app stay organized and clean.
Now, when playing around with angular, I see that in many examples they use <script> to load these modules.
Is there a clean way to load modules without using this <script> tag? and keep angular functioning as expected?
Is it common to use require-js for angularjs apps? or is there any alternative?
Thanks.

You don't need to use require since you have a built in dependency injection mechanism. In order to use 3rd party libraries you need to do 3 things:
Use libraries that are compatible with angular in order be synced with the digest cycle. Most of the common libraries have an angular module that encapsulates their code.
Add these modules to your app. You can explicitly add each library with its own script tag or you can create a bundle of all your libraries and include only it.
Declare the use of that module when you create your app and module.

Angular uses whats called dependency injection to handle modules. Here is the documentation: https://docs.angularjs.org/guide/module

You might want to look at https://github.com/substack/node-browserify#usage
The downside is you'll introduce a "compile phase" to your build process.
The plus is the npm integration.
You still need to follow the "angular way" to inject dependencies, using browserify you'll have little yet nice puses https://blog.codecentric.de/en/2014/08/angularjs-browserify/
Hope it helps.

Related

Does vanilla JS project mean the project that was done without using any library or framework?

I used three.js, gsap, and mobx(a global state management library). Can't I just call this a vanilla JS project?
Vanilla JS is a way of saying that the Javascript code is written without any libraries or dependencies.
Since you used three.js, gsap, and mobx, your project is not vanilla JS.
If I was looking for a job and a potential employer claims I'd work on an vanilla js project, I would not feel deceived if:
the overall structure of the project is not dictated by the library (which excludes angular, react, etc.).
used libraries have a limited scope and therefore are more or less easily exchangeable (you can switch from chart.js to d3.js)
I can understand, reason about and write code in an application logic module without looking up any documentation for the libraries used by the other modules (that's decoupling)
the removal of a library does not force you to rewrite your whole codebase
There is an exception to the last rule: legacy codebases that depend on libraries like jQuery or underscore: I'd call a project "vanilla" if the team is committed to remove these dependencies and new modules are written without these dependencies.
In your case presentation (three.js) and animations (gasp) should be decoupled from logic. But MobX seems to be the deal breaker: it plugs deep into your classes and logic. This is not vanilla. In order to understand your code, a new developer not only has to look at your code, but also at the documentation for MobX.
Allthough MobX says "MobX is unopinionated and allows you to manage your application state outside of any UI framework." The first example they present is obviously react code, which repels me.

convert angular 2 application to integrate able sdk

i have a angular 2 application. I was wondering if i could convert this application to an integrate-able sdk which other applications can use by adding script tags in their headers. If this is not possible can anyone provide any tutorial link which shows how can i build a simple sdk which can be integrated in other applications. thank you.
Of course you can! In javascript terms, it's not called "SDK" but "module".
The most popular module manager is called NPM.
So you can follow this tutorial to package your "application" as NPM module, then it will be easy for other js developper to integrate it inside their own projects (using the tags, services, directives you defined.
Here is a good post about it
Cheers!
EDIT : if you want to use your angular components/modules outside in non-angular application, you can follow this one. In the example it is used with React app but it will work with any html5-compliant browsers.
If you want to target also non-compatible browsers, you should add a polyfill

Should I concatenate my dependencies on my Javascript library?

I'm working on a JS library that relies heavily on D3 (and to some extent, lodash). I've modularized it, have bower_components for the external library dependencies and node and gulp for the build/concatenation/uglifying process. So I'm covered from the development standpoint (no need for require.js).
However, in order to let other people use my library, they need to have both d3 and loadash loaded. I don't want to bloat their loading but at the same time I want to make things easy for everyone. Should I just concatenate my dependencies along with my .min.js and have that be a release? What are the best practices?
BTW, my current versions of lodash and d3 clock in at 52k and 148k respectively. Thanks!
I seems interesting to embed dependencies in your own library to offer customers an easier way to integrate your component, but think about that:
They may use another component requiring a more up-to-date D3 (you embedded)
For performance reason at load time, your customer may want to use D3 (or other embedded libraries) using the official CDN (better access and downloading time)
You will have to carry about updating your component each time one of your dependency is fixed.
For other more reason you could find by yourself, it is not a good practice to embed dependencies inside your component unless you plan to manage a full support of it.

Using Asynchronous Module load in javascript library project

I am working on an javascript project which will be provided as a third-library.
And there are a lot of modules and templates which is a waste of time and performance if loading them all at once. So I think use a module loader like requirejs maybe a good idea.
However since the project will be use by other people, so how about the client use requirejs at the same time?
Since I have to config the dependencies for my own library, while the client need to config the dependencies for his project. I am afraid this will cause some conflict.
Any alternatives?
And there are a lot of modules and templates which is a waste of time and performance if loading them all at once.
It sounds like you are opting to not use r.js to optimize your library. This is a choice you can make. However, you will have to document your library so that people using it can produce a RequireJS configuration that will take care of the needs of their own code and the needs of your library. You should provide an example of RequireJS configuration that satisfies your library and people wanting to use it can integrate that configuration with their own.
If you were to optimize your library with r.js, then you could use Almond to load your library as a single unit, and hide the fact that it is a collection of AMD modules. However, this entails "loading them all at once", which you do not want.

Does it make sense to use Require.js with Angular.js? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm a newbie to Angular.js and trying to understand how it's different from Backbone.js... We used to manage our packages dependencies with Require.js while using Backbone. Does it make sense to do the same with Angular.js?
Yes it makes sense to use angular.js along with require.js wherein you can use require.js for modularizing components.
There is a seed project which uses both angular.js and require.js.
To restate what I think the OP's question really is:
If I'm building an application principally in Angular 1.x, and (implicitly) doing so in the era of Grunt/Gulp/Broccoli and Bower/NPM, and I maybe have a couple additional library dependencies, does Require add clear, specific value beyond what I get by using Angular without Require?
Or, put another way:
"Does vanilla Angular need Require to manage basic Angular component-loading effectively, if I have other ways of handling basic script-loading?"
And I believe the basic answer to that is: "not unless you've got something else going on, and/or you're unable to use newer, more modern tools."
Let's be clear at the outset: RequireJS is a great tool that solved some very important problems, and started us down the road that we're on, toward more scalable, more professional Javascript applications. Importantly, it was the first time many people encountered the concept of modularization and of getting things out of global scope. So, if you're going to build a Javascript application that needs to scale, then Require and the AMD pattern are not bad tools for doing that.
But, is there anything particular about Angular that makes Require/AMD a particularly good fit? No. In fact, Angular provides you with its own modularization and encapsulation pattern, which in many ways renders redundant the basic modularization features of AMD. And, integrating Angular modules into the AMD pattern is not impossible, but it's a bit... finicky. You'll definitely be spending time getting the two patterns to integrate nicely.
For some perspective from the Angular team itself, there's this, from Brian Ford, author of the Angular Batarang and now a member of the Angular core team:
I don't recommend using RequireJS with AngularJS. Although it's certainly possible, I haven't seen any instance where RequireJS was beneficial in practice.
So, on the very specific question of AngularJS: Angular and Require/AMD are orthogonal, and in places overlapping. You can use them together, but there's no reason specifically related to the nature/patterns of Angular itself.
But what about basic management of internal and external dependencies for scalable Javascript applications? Doesn't Require do something really critical for me there?
I recommend checking out Bower and NPM, and particularly NPM. I'm not trying to start a holy war about the comparative benefits of these tools. I merely want to say: there are other ways to skin that cat, and those ways may be even better than AMD/Require. (They certainly have much more popular momentum in late-2015, particularly NPM, combined with ES6 or CommonJS modules. See related SO question.)
What about lazy-loading?
Note that lazy-loading and lazy-downloading are different. Angular's lazy-loading doesn't mean you're pulling them direct from the server. In a Yeoman-style application with javascript automation, you're concatenating and minifying the whole shebang together into a single file. They're present, but not executed/instantiated until needed. The speed and bandwidth improvements you get from doing this vastly, vastly outweigh any alleged improvements from lazy-downloading a particular 20-line controller. In fact, the wasted network latency and transmission overhead for that controller is going to be an order of magnitude greater than the size of the controller itself.
But let's say you really do need lazy-downloading, perhaps for infrequently-used pieces of your application, such as an admin interface. That's a very legitimate case. Require can indeed do that for you. But there are also many other, potentially more flexible options that accomplish the same thing. And Angular 2.0 will apparently take care of this for us, built-in to the router. (Details.)
But what about during development on my local dev boxen?
How can I get all my dozens/hundreds of script files loaded without needing to attach them all to index.html manually?
Have a look at the sub-generators in Yeoman's generator-angular, or at the automation patterns embodied in generator-gulp-angular, or at the standard Webpack automation for React. These provide you a clean, scalable way to either: automatically attach the files at the time that components are scaffolded, or to simply grab them all automatically if they are present in certain folders/match certain glob-patterns. You never again need to think about your own script-loading once you've got the latter options.
Bottom-line?
Require is a great tool, for certain things. But go with the grain whenever possible, and separate your concerns whenever possible. Let Angular worry about Angular's own modularization pattern, and consider using ES6 modules or CommonJS as a general modularization pattern. Let modern automation tools worry about script-loading and dependency-management. And take care of async lazy-loading in a granular way, rather than by tangling it up with the other two concerns.
That said, if you're developing Angular apps but can't install Node on your machine to use Javascript automation tools for some reason, then Require may be a good alternate solution. And I've seen really elaborate setups where people want to dynamically load Angular components that each declare their own dependencies or something. And while I'd probably try to solve that problem another way, I can see the merits of the idea, for that very particular situation.
But otherwise... when starting from scratch with a new Angular application and flexibility to create a modern automation environment... you've got a lot of other, more flexible, more modern options.
(Updated repeatedly to keep up with the evolving JS scene.)
Yes, it makes sense.
Angular modules don't try to solve the problem of script load ordering
or lazy script fetching. These goals are orthogonal and both module
systems can live side by side and fulfil their goals.
Source: Angular JS official website
This I believe is a subjective question, so I will provide my subjective opinion.
Angular has a modularization mechanism built in. When you create your app, the first thing you would do is
var app = angular.module("myApp");
and then
app.directive(...);
app.controller(...);
app.service(...);
If you have a look at the angular-seed which is neat starter app for angular, they have separated out the directives, services, controllers etc into different modules and then loaded those modules as dependancies on your main app.
Something like :
var app = angular.module("myApp",["Directives","Controllers","Services"];
Angular also lazy loads these modules ( into memory) not their script files.
In terms of lazy loading script files, to be frank unless you are writing something extremely large it would be an overkill because angular by its very nature reduces the amount of code you write. A typical app written in most other frameworks could expect a reduction in around 30-50% in LOC if written in angular.
Using RequireJS with AngularJS makes sense but only if you understand how each of them works regarding dependency injection, as although both of them injects dependencies, they inject very different things.
AngularJS has its own dependency system that let you inject AngularJS modules to a newly created module in order to reuse implementations. Let's say you created a "first" module that implements an AngularJS filter "greet":
angular
.module('first', [])
.filter('greet', function() {
return function(name) {
return 'Hello, ' + name + '!';
}
});
And now let's say you want to use the "greet" filter in another module called "second" that implements a "goodbye" filter. You may do that injecting the "first" module to the "second" module:
angular
.module('second', ['first'])
.filter('goodbye', function() {
return function(name) {
return 'Good bye, ' + name + '!';
}
});
The thing is that in order to make this work correctly without RequireJS, you have to make sure that the "first" AngularJS module is loaded on the page before you create the "second" AngularJS module. Quoting documentation:
Depending on a module implies that required module needs to be loaded
before the requiring module is loaded.
In that sense, here is where RequireJS can help you as RequireJS provides a clean way to inject scripts to the page helping you organize script dependencies between each other.
Going back to the "first" and "second" AngularJS modules, here is how you can do it using RequireJS separating the modules on different files to leverage script dependencies loading:
// firstModule.js file
define(['angular'], function(angular) {
angular
.module('first', [])
.filter('greet', function() {
return function(name) {
return 'Hello, ' + name + '!';
}
});
});
// secondModule.js file
define(['angular', 'firstModule'], function(angular) {
angular
.module('second', ['first'])
.filter('goodbye', function() {
return function(name) {
return 'Good bye, ' + name + '!';
}
});
});
You can see that we are depending on "firstModule" file to be injected before the content of the RequireJS callback can be executed which needs "first" AngularJS module to be loaded to create "second" AngularJS module.
Side note: Injecting "angular" on the "firstModule" and "secondModule" files as dependency is required in order to use AngularJS inside the RequireJS callback function and it have to be configured on RequireJS config to map "angular" to the library code. You may have AngularJS loaded to the page in a traditional manner too (script tag) although defeats RequireJS benefits.
More details on having RequireJS support from AngularJS core from 2.0 version on my blog post.
Based on my blog post "Making sense of RequireJS with AngularJS", here is the link.
As #ganaraj mentioned AngularJS has dependency injection at its core. When building toy seed applications with and without RequireJS, I personally found RequireJS was probably overkill for most use cases.
That doesn't mean RequireJS is not useful for it's script loading capabilities and keeping your codebase clean during development. Combining the r.js optimizer (https://github.com/jrburke/r.js) with almond (https://github.com/jrburke/almond) can create a very slim script loading story. However since its dependency management features are not as important with angular at the core of your application, you can also evaluate other client side (HeadJS, LABjs, ...) or even server side (MVC4 Bundler, ...) script loading solutions for your particular application.
Yes, it does, specially for very large SPA.
In some scenario, RequireJS is a must. For example, I develop PhoneGap applications using AngularJS that also uses Google Map API. Without AMD loader like RequireJS, the app would simply crash upon launch when offline as it cannot source the Google Map API scripts. An AMD loader gives me a chance to display an error message to the user.
However, integration between AngularJS and RequireJS is a bit tricky. I created angularAMD to make this a less painful process:
http://marcoslin.github.io/angularAMD/
Short answer is, it make sense. Recently this was discussed in ng-conf 2014. Here is the talk on this topic:
http://www.youtube.com/watch?v=4yulGISBF8w
It makes sense to use requirejs with angularjs if you plan on lazy loading controllers and directives etc, while also combining multiple lazy dependencies into single script files for much faster lazy loading. RequireJS has an optimisation tool that makes the combining easy. See http://ify.io/using-requirejs-with-optimisation-for-lazy-loading-angularjs-artefacts/
Yes it makes sense to use requireJS with Angular, I spent several days to test several technical solutions.
I made an Angular Seed with RequireJS on Server Side. Very simple one.
I use SHIM notation for no AMD module and not AMD because I think it's very difficult to deal with two different Dependency injection system.
I use grunt and r.js to concatenate js files on server depends on the SHIM configuration (dependency) file. So I refer only one js file in my app.
For more information go on my github Angular Seed :
https://github.com/matohawk/angular-seed-requirejs
I would avoid using Require.js. Apps I've seen that do this wind up a mess of multiple types of module pattern architecture. AMD, Revealing, different flavors of IIFE, etc. There are other ways to load on demand like the loadOnDemand Angular mod. Adding other stuff just fills your code full of cruft and creates a low signal to noise ratio and makes your code hard to read.
Here is the approach I use: http://thaiat.github.io/blog/2014/02/26/angularjs-and-requirejs-for-very-large-applications/
The page shows a possible implementation of AngularJS + RequireJS, where the code is split by features and then component type.
Answer from Brian Ford
AngularJS has it's own module system an typically doesn't need something like RJS.
Reference: https://github.com/yeoman/generator-angular/issues/40
I think that it depends on your project complexity since angular is pretty much modularized.
Your controllers can be mapped and you can just import those JavaScript classes in your index.html page.
But in case your project get bigger. Or you anticipates such scenario, you should integrate angular with requirejs. In this article you can see a demo app for such integration.

Categories

Resources