Load external modules (third party libs) in Angularjs

时间:2016-04-04 16:40:57

标签: javascript angularjs requirejs

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.

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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:

  1. 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.

  2. 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.

  3. Declare the use of that module when you create your app and module.

答案 2 :(得分:1)

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.