博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AngularJS + RequireJS
阅读量:5745 次
发布时间:2019-06-18

本文共 7250 字,大约阅读时间需要 24 分钟。

http://www.startersquad.com/blog/-requirejs/

 

While delivering , we’ve come to love . We’ve also come to struggle with clean modularity, both the parts that Angular does really well, and the parts that are somewhat missing. RequireJS does a great job where Angular leaves some things to be desired, but using them together is not entirely trivial. What follows is our take at the problem.

Why?

Working with Angular you could worry about a good way to organize code. There are already great how-tos on that, check out  by Brian Ford and  by Cliff Meyers if you haven’t already. I’ll share the way I’m managing code in Angular applications with RequireJS.

Continue reading if you want to:

  • stop worrying about including script tags in the right order when building Angular apps;
  • to load your javascript asynchronously;
  • to compile code into single minified js file;

Who?

I assume that you already know what AngularJS is and that you’ve at least heard of AMD and RequireJS. To illustrate the approach I’ll first enable RequireJS for  and explain process. Angular Seed structures code by splitting files by type and so will I. It’s also possible to apply this approach if you write modules by entities (you’ll see it from app.controllersmodule implementation).

How?

Angular Seed Project

Let’s check how Angular Seed structures code. Check out the example  or  (copied from Seed):

  • app.js file to bootstrap and set app config;
  • actual implementation files – controllers, services, directives and filters;
  • index.html with all script tags included in right order;
  • or index-async.html that makes use of angular-loader.js and 3-rd party$script loader library to load dependencies asyncronously.

Let’s start the party.

Add RequireJS

Checkout the example  or .

Installing dependencies

I used  to do this for me. See bower.json file:

{  "name": "AngularJS + RequireJS Example",  "version": "0.1",  "main": "index.html",  "ignore": [    "**/.*",    "libs"  ],  "dependencies": {    "angular": "latest",    "requirejs": "latest",    "requirejs-domready": "latest"  }}

Put the .bowerrc file next to bower.json, run bower install and – poof, we have all we need under libs folder.

index.html

Destruction is a good start. Open Angular Seed’s index.html and remove all the <script> tags. Looks cleaner, doesn’t it? Now switch to creation mode and add single script before closing </body> that will load RequireJS and instruct it to look for config in /main.js with the :

  
My AngularJS AngularJS + RequireJS App
Angular Require seed app: v

That’s all there’s to it. You can close index.html now, as there is nothing more we need to add to it.

main.js

Time to setup RequireJS config.

require.config({  // alias libraries paths    paths: {        'domReady': '../lib/requirejs-domready/domReady',        'angular': '../lib/angular/angular'    },    // angular does not support AMD out of the box, put it in a shim    shim: {        'angular': {            exports: 'angular'        }    },    // kick start application    deps: ['./bootstrap']});

What just happened? In  we set aliases for the libraries and plugins used, then we defined that angular should be  and thatbootstrap.js should be loaded to start the application.

bootstrap.js

We’re bootstrapping angular manually now, that’s what bootstrap.js is for. Note that you don’t need ng-app in your html anymore. Also routes.js, which contains angular routes configuration is included into dependencies list.

Note that in this require module we almost have no use of asynchronous loading and we’ll always have chain of angular -> app -> routes, as they depend on each other: angular needs to be present on a page before setting up application module, which is required to exist when defining routes config.

/** * bootstraps angular onto the window.document node */define([    'require',    'angular',    'app',    'routes'], function (require, ng) {    'use strict';    require(['domReady!'], function (document) {        ng.bootstrap(document, ['app']);    });});

We use  RequireJS plugin to make sure that DOM is ready when we start the app. Note that before doing so we’re loading the app.jsdependency, in there the main application is defined.

app.js

app.js wraps the definition of the top-level app module and loads the dependencies of its submodules.

define([    'angular',    './controllers/index',    './directives/index',    './filters/index',    './services/index'], function (ng) {    'use strict';    return ng.module('app', [        'app.services',        'app.controllers',        'app.filters',        'app.directives'    ]);});

We agreed to have 4 modules by files types: controllers, directives, filters, services – we require these modules to be loaded before defining the main module.

routes.js

Top level routes definition lives here. It is also possible to have modules to set up their own routes (this case is omitted for now in favour of simplicity).

define(['./app'], function (app) {    'use strict';    return app.config(['$routeProvider', function ($routeProvider) {        $routeProvider.when('/view1', {            templateUrl: 'partials/partial1.html',            controller: 'MyCtrl1'        });        $routeProvider.when('/view2', {            templateUrl: 'partials/partial2.html',            controller: 'MyCtrl2'        });        $routeProvider.otherwise({            redirectTo: '/view1'        });    }]);});

Module structure

A module consists of 3 parts:

  • definition;
  • component;
  • loader.

Let’s use the app.controllers module as example.

module definition (controllers/module.js)

It’s just like top level app.js: it defines a module.

define(['angular'], function (ng) {    'use strict';    return ng.module('app.controllers', []);});

This file will be used by the module components to attach themselves to (see next section).

module loader (controllers/index.js)

That’s just an empty define block with all module components included. You don’t need to mention module.js here as it’s already required by components. Loader is included as dependency of top level app module. And that’s actually how RequireJS knows about files to load.

define([    './my-ctrl-1',    './my-ctrl-2'], function () {});

module components (controllers/my-ctrl-1.js)

In the case with the app.controllers module it’ll be controllers. Example of controller wrapped in define is:

define(['./module'], function (controllers) {    'use strict';    controllers.controller('MyCtrl1', [function ($scope) {}]);});

Note that we used reference to ./module.js to attach component to its module.

Conclusion

That’s it. Now you have working Angular application powered by RequireJS. You can enjoy the power of not tracking the order of your scripts anymore and you get some powerful minification tooling to boot.

In next articles I’ll show you how to test this application properly, how to compile it into single file and automate workflows with grunt. All this is already enabled in  check it out if you can’t wait (I’m a slow typist).

About StarterSquad

StarterSquad is a community of distributed development teams consisting of freelance developers. We specialize in  and . If you want to know more, read  and if you need any help with Angular, checkout my .

转载地址:http://roxzx.baihongyu.com/

你可能感兴趣的文章
18 已知下面的字符串是通过RANDOM随机数变量md5sum|cut-c 1-8截取后的结果
查看>>
BZOJ - 3578: GTY的人类基因组计划2
查看>>
爱——无题
查看>>
分布式服务框架原来与实践 读书笔记一
查看>>
【http】post和get请求的区别
查看>>
TFS强制撤销某个工作区的文件签出记录
查看>>
EL表达式无法显示Model中的数据
查看>>
ps6-工具的基础使用
查看>>
linux下使用过的命令总结(未整理完)
查看>>
时间助理 时之助
查看>>
英国征召前黑客组建“网络兵团”
查看>>
PHP 命令行模式实战之cli+mysql 模拟队列批量发送邮件(在Linux环境下PHP 异步执行脚本发送事件通知消息实际案例)...
查看>>
pyjamas build AJAX apps in Python (like Google did for Java)
查看>>
centos5.9使用RPM包搭建lamp平台
查看>>
Javascript String类的属性及方法
查看>>
[LeetCode] Merge Intervals
查看>>
Struts2 学习小结
查看>>
测试工具综合
查看>>
【记录】JS toUpperCase toLowerCase 大写字母/小写字母转换
查看>>
在 Linux 系统中安装Load Generator ,并在windows 调用
查看>>