what are the advantages of using an AMD like requirejs or commonjs modules in javascript?

Matteo Pagliazzi picture Matteo Pagliazzi · Aug 19, 2012 · Viewed 7.1k times · Source

I've read a lot of articles on AMD solutions like RequireJS or module loaders that follow CommonJS style in Javascript.

Let's say I have an app splitted in this parts:

  • App definition that rely on the framework i use
  • Model 1 that rely on App definition and framework
  • Model 2 that rely on App definition, Model 1 and my framework

I may write each part as a RequireJS module or a common JS module and split my project in how many files I want but what's the advantage of writing each part as a module or splitting them in many files and then load them in the right order (to avoid dependency problems) maybe concatenatening all the files in a big one to reduce HTTP requets (as done by r.js optimizer)?

Answer

Peeter picture Peeter · Aug 19, 2012

In my opinion, there are three rather important reasons:

You can create and re-use modules without polluting the global namespace. The more polluted your global namespace is, the bigger the chance of a function/variable collision. That means you define a function called "foo" and another developer defines the function "foo" = one of the functions gets overwritten.

You can structure your code into separate folders and files and requirejs will load them asynchronously when needed, so everything just works.

You can build for production. RequireJS comes with its own build tool called R.JS that will concat and uglify your javascript modules into a single (or multiple) packages. This will improve your page speed as the user will have to make less script calls and load less content (as your JS is uglified).

You can take a look at this simple demo project: https://c9.io/peeter-tomberg/requirejs (in cloud9ide).

To build your modules into a single app, all you have to do is have requirejs npm package installed and run the command: r.js -o build/build.properties.js

If there are any questions, ask away.

Edit:

In development, having all modules in separate files is just a good way to structure and manage your code. It also helps you in debugging (e.g. error on "Module.js line 17" instead of "scripts.js line 5373").

For production, you should use the build tool to concat and uglify the javascript into a single file. This will help the page load quicker as you are making less requests. Every request you make to load something slows down your page. The slower your page, the less points Google gives you. The slower the page, the more frustrated your users will be. The slower your page, the less sales you will get.

If you wish to read more about web page performance, look at http://developer.yahoo.com/performance/rules.html