AngularJS - 使用RequireJS或内置的模块化开发?

Mar*_*tin 6 amd requirejs angularjs

我一直在写一个angularjs应用程序,我有一些控制器,我已经放在1 JS文件中.我希望有一些更模块化的东西,并将我的控制器分成自己的文件.

我想到了RequireJS,但这是推荐的方式吗?或者angularjs是否提供了其他内容以及任何解释位置的线索?

也有所有这些文件进行调试是伟大的,但一旦生产建设需要确实angularJS提供某种合并的模块为1个文件,结果最小化?

如果有人能解释最好的方法,那将是非常有帮助的.

谢谢

max*_*dec 12

Angular依赖注入非常棒,你应该创建很多小模块.

说到文件组织,更容易拥有很多小文件(每个模块可能有一个),但是你面对的问题是:我怎么处理所有这些文件?我如何加载它们?

值得一看的是这两个来源:Brian Ford的博客这个Github回购.它帮助我改进了我的工作流程并更好地理解/使用Angular模块.

TL; DR

我为我的项目做的是使用咕噜Concat的(再压缩如果需要的话)的所有js文件(和方式更多:更少的CSS编辑,资产管理,JavaScript的模板编译).
上面的Github回购中给出了一个很好的例子.

我不建议将RequireJS与AngularJS一起使用.虽然这当然是可能的,但我还没有看到任何RequireJS在实践中有益的例子.[布莱恩福特]

文件组织

我的app文件夹如下所示:

www
|-dist/         = Created by Grunt. Generated files (served by my web server).
|-node_modules/ = node modules (ie. Grunt modules. Grunt is based on NodeJS)
|-src/          = My workspace
|-test/         = Some tests
|-vendor        = External libraries (AngularJS, JQuery, Bootstrap, D3, ... Whatever you need)
|-gruntFile.js  = The Grunt configuration file: contains all the jobs for Grunt.
|-package.json  = App infos + dependencies (Grunt modules) I use (concat, uglify, jshint, ...)
Run Code Online (Sandbox Code Playgroud)

所以我处理的所有不同文件都在src文件夹中,然后看起来像这样:

www/src
|-app              = Folder for my controllers
| |-Controller1.js
| |-Controller2.js
| |-...
|-assets           = Folder for the static assets (img, css, ...)
| |-img/
| |-css/
| |-favicon.ico
|-common           = Folder for the shared modules (directives, resources, services, ...)
| |-directives
| | |-chart.js
| | |-map.js
| | |-...
| |-resources
| | |-users.js
| | |-another-cool-resource.js
| | |-...
| |-services
| | |-service1.js
| | |-...
|-views            = Folder for my templates
| |-profile.tpl.html
| |-search.tpl.html
| |-...
|-index.html       = The main and unique html file.
Run Code Online (Sandbox Code Playgroud)

咕噜

然后我使用Grunt将所有内容"编译"到dist文件夹中.这里可以找到
一个例子.我有一次性的部署工作和一些观察者的发展. gruntFile

你需要更多解释吗?

  • 使用RequireJS有许多优点(并行下载,缓存......).我喜欢它是因为我可以控制应用程序的哪个部分加载.如果用户只访问某个部分(例如,基于用户权限),为什么要加载整个应用程序.所以我不会说RequireJS没用.它确实在特定情况下很有用...... (3认同)