The past and present of JavaScript modularity


The modularity of Javascript includes CMD, AMD, UMD, CommonJS, ES Module and other specifications. The CommonJS specification is used for NodeJS modularization.

We won’t go into the details of the above modularity scenarios here; we’ll focus on the definition of the Type attribute in package.json.

NodeJS supports ES6 modularity

In earlier nodeJS versions, Node only supported Commonjs modularity, but in NodeJS version 13.2.0, Node officially supports ES Modules modularity, declaring the Type field in package.json

{
  "type": "module"."scripts": {
    "start": "node index.js"."test": "echo \"Error: no test specified\" && exit 1"}}Copy the code

Conclusion shows that

  1. The type field defines the modular processing specification for package.json files and.js files and files without extensions in the root directory of the file. The default value is ‘commonjs’.
  2. If the type field is omitted, the commonJS specification is adopted by default
  3. When the type field is set to module, the ESModule specification is adopted
  4. The node official recommendation package developer explicitly specifies the type field value in package.json
  5. Json,.mjs files are treated according to es module,.cjs files are treated according to commonJS module