2
votes

I apologise in advance if the question has been already answered but I haven't been able to find anything relevant. I'm refactoring a fairly large AngularJS application, I'm creating components in form of AMD modules. The build process (grunt) uses requirejs plugin to load all the modules and concatenate them into a single js file including some libraries like jQuery.

Now, I was looking at the CommonJS syntax and it looks very much more clean and I was wondering if it is worth to use CommonJS modules instead of AMD. I see that the build process wouldn't be too different, basically I just need to swap requireJS with browserify.

Are there any advantages in using AMD modules over commonJS one in a workflow like mine? Can the asynchronous module loading be still considered an advantage at runtime when you're concatenating all the modules in a single js file?

Thanks.

1
when you're concatenating all the modules in a single js file then no. you are right no need for AMD, doesnt make any sense actually. Also read requirejs.org/docs/commonjs.htmlvinayakj
Another option you should consider is Webpack which supports AMD, CommonJS and ES6 module systems.Davin Tryon
Like vinyakj writes, if concatenating to one file, no need for AMD. If however you would care for some lazy-loaded code, you may take a look at angular-require-lazy for some ideas.Nikos Paraskevopoulos

1 Answers

1
votes

Nowadays I would recommend you to look into ES2015 modules as native module system in JavaScript. It has both - the simplicity of syntax like CommonJS and asynchronously loaded modules like AMD.

// my-module.js
export const foo = "foo";
export function bar() { return "bar"; };

...

// main.js
import { foo, bar } from "./my-module.js";
console.log( foo, bar() );

Natively it is supported at the moment only by Chrome 60+, but you make it working in any browser with Webpack or SystemJS. I personally care much of progressive enhancement and keen to deliver the core user experience with the "first bytes". In this regard I like most about the ability to combine both approaches (compiled synchronous and loaded asynchronous modules) in one app for the best performance (with Webpack). So you decide what of modules get compiled in a single file and which you load on demand (given you control how they load).

Promise.all([
 import("./module-foo" ),
 import("./module-bar" ),
 import("./module-baz" )
]).then( moduleExports => {
  console.log( moduleExports );
}).catch(( e )=> {
  console.error( e );
});

In this blog post https://medium.com/@sheiko/state-of-javascript-modules-2017-6548fc8af54a I described how exactly one can achieve it. Enjoy!