How are UMD and CommonJS (CJS) package folders different, and which should I use?

JavaScript was originally for interactive browsers only. With NodeJS, it is used in non-browser contexts. Because of this and other factors, there are incompatible formats for modules:

  • The “CommonJS” specification describes the use of an exports object which is the API to declare and discover what names are exported from a module. No allowance is made for loading a CommonJS module in an interactive browser. NodeJS is the most popular implementation of the CommonJS format.

  • The “Asynchronous Module Definition” (AMD) describes how to bundle JavaScript modules on the assumption they will be loaded in an interactive browser. RequireJS is one of the more popular module-support libraries, and it consumes AMD modules.

  • Because AMD and CommonJS are both very popular and mutually unintelligible to each other, the “Universal Module Definition” (UMD) is a pattern to make a module that can be consumed by both, at the cost of a more complicated format.

  • More recently, ECMAScript 2015 defines export and import syntax (different from all the above) to support modules.

Which should you use? You’ll need to answer that based on what in your build system will be consuming those modules.

Today (2022-02), the most likely answer is: use ECMAScript modules, which are now supported for years, in NodeJS and major browsers.

If you need to support very outdated JavaScript engines you might need one of the earlier formats, but you should have a schedule to drop support for those.

Leave a Comment

404 Not Found

Not Found

The requested URL was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.