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

kust kust picture kust kust · Jul 8, 2018 · Viewed 9.3k times · Source

I installed reactjs and react-dom like this with package.json

"dependencies": {
   "bootstrap": "^v4.1.1",
   "popper.js": "^1.14.3",
   "react": "^v16.4.1",
   "react-dom": "^16.4.1"
}

It downloaded react folder and react-dom folder correctly.

Both folders have cjs and umd folder and they have a lot of js files.

For me it's unable to find difference between files in two folders.

Like this:

URL: node_modules/react/umd
  react-development.js
  react-production.min.js



URL : node_modules/react/cjs
   react-development.js
   react-production.min.js

almost same with react-dom. It also has cjs and umd folder and I don't know which file from which folder should I use to develop a react application or website.

Answer

bignose picture bignose · Apr 12, 2019

JavaScript was originally for interactive browsers only. With Node, 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 that attempts 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, the most likely answer is: use the UMD module. Some time in the future it may be: use ECMAScript modules; but we don't yet (2019) have consensus on how those will be distributed.