Nodejs module loader vs client-side AMD loader like Requirejs

383 Views Asked by At

This question is about loading Javascript modules on the client-side. Two popular means of achieving this is by using:

  1. RequireJS
  2. NPM (Node Package Manager) to export and require files

The first option has always worked great for me. However, recently I noticed more and more people using the second option.

When I tried out the second option using a build tool (browserify) I noticed the files that were build contained a lot of redundant code like a wrapper around my own code. Now I'm not sure if this is the best option, cause if all my javascript files were modified in such fashion the overall size of my project will increase and so will the load time. Is this something I should be worried about? Are there any other differences between the two options?

1

There are 1 best solutions below

0
On

The main reasons to use CommonJS (the Node.js module system) are, in my opinion:

  1. You enjoy the Node.js eco system - especially NPM (easy dependancy management, great modular design) but also things like frameworks which are only available for CommonJS/Node.js code (mocha etc.).
  2. It allows you to share code between client and server easily (it's the exact same code). With requirejs it is not the case (not directly at least). This is usually not really useful but it can help in some rare cases.

Once big difference between CommonJS + Browserify and requirejs, is that the former bundles all the code into one large file. You cannot load modules asynchronously like you could with requirejs. This is not always a bad thing (one might argue that a single request for a JS is better then multiple ones, even if the single request resulted in some code that is not actually used).

About the size question: with requirejs, you also have quite some overhead (for one, you have to include the require.js script, which is similar to the additions that you have seen created by Browserify). Both are quite negligible in most cases but it depends on what you are building of course.