🌟🌟🌟🌟🌟

Taste: Lotus root with sesame paste

Cooking time: 10min

CSS introduced @import as early as version 2.1 to implement modularity, but JavaScript didn’t get the official modularity solution ES Module until ES6. Although modularity was not supported by the early JavaScript language specifications, this has not stopped JavaScript from evolving. There is no official modular standard, so we will create our own. Predecessors in the community created and implemented specifications that were the brainchild of the modular development of the front end.

The value of modularity

Today in 2020, modularity should have the following value:

  • maintainability
  • Reduce global pollution
  • reusability
  • Easy to manage dependencies
  • The practice of divide and conquer

A decade ago, modularity was simply implementing a namespace using “closures.” This solution makes it easy to handle global variables and dependencies.

The concept of closures can be found in another of my articles.

CommonJS


Let’s go back to January 2009, when everything started to grow in the middle of an ordinary winter. The Kunlun Station of the China Antarctic Scientific Research Station was completed, becoming the highest scientific research station in the Antarctic. Within the JavaScript community, Mozilla engineer Kevin Dangoor initiated the CommonJS proposal. (Originally called ServerJS)

Then came Node.js, which adopted the CommonJS modular specification and brought with it NPM (the world’s largest module repository).

Nodejs modules are not implemented exactly as CommonJS specifications, but rather as trade-offs with a few additional features.

The CommonJS specification performs well on the server side, making JavaScript shine on the server side, competing with or even overtaking traditional server languages such as PHP and Python. Programmers came up with the idea of porting it to the browser.

However, since CommonJS modules are loaded synchronously. As we know, modules loaded on the server side are loaded from memory or disk and take negligible time. However, on the browser side, it will cause blocking, white screen time is too long, and user experience is not friendly.

As a result, some branches gradually emerged from CommonJS, which are also known as AMD, CMD and so on.

AMD specification


“James Burke” came up with the AMD specification, RequireJS is his masterpiece. He also developed Amdefine, a library that can use the AMD specification in Node.

AMD is addressing the CommonJS specification’s shortcomings in browsers:

  • Lack of module encapsulation capability
  • Load dependencies synchronously
  • exportCan only export variables, export functions need to usemodule.export(This is often counterintuitive)

The AMD specification defines a define global method for defining and loading modules, and RequireJS later extended the Require global method for loading modules. “The core implementation is the internal module loader.”

CMD specification


“@Yubo” proposed sea-.js (an implementation of the CMD specification).

To be precise, CMD is the normalized product of the SeaJS module definition during the promotion process.

CMD is more lazy than AMD’s asynchronous loading, and the specification itself is closer to CommonJS.

Because of the lazy loading mechanism, sea.js provides the seajs.use method to run defined modules. All callbacks to define are not executed immediately. Instead, all callbacks to define are cached. Only callbacks to use and required modules are executed.

RequireJS and Sea-.js

  • sea.jsOnly in therequireWhere the module will actually be executed.
  • RequireJSAll dependencies are run and all results are obtained before the callback is executed.

AMD is different from CMD

  • For dependent modules,AMDIs ahead of schedule,CMDDelayed execution.
  • CMDAdvocate relying on proximity,AMDRely on the front.
  • AMDAPIOne when multiple use, single responsibility.CMDEach API is simple and pure.

Answer from @Yubo

UMD

UMD is a combination of AMD and CommonJS. AMD for browsers, CommonJS for servers. UMD is the compatible mode of the two, which solves the problem of cross-platform.

Implementation principle: if-else

For details, go to githubUMD

ES Module

Long periods of separation make great progress.

Ten years later, the official dad came out with the ES6 modular solution, a unified browser and server. The module is loaded in a completely static way.

grammar

Module import

// Import the default module
// main.js
import name from './module.js'
Copy the code

// module.js const name = 'Front Canteen' export default name

// If you want to import other modules
// main.js
import { name, getName } from './module.js'

// module.js
export const name = 'Front Canteen'
export const getName = (a)= > name
Copy the code
// Import simultaneously
// main.js
import  name, { getName } from './module.js'

// module.js
const name = 'Front Canteen'
export const getName = (a)= > name
export default name
Copy the code
/ / renamed
// main.js
import * as mod from './module.js'
let name = ' '
name = mod.name
name = mod.getName()

// module.js
export const name = 'Front Canteen'
export const getName = (a)= > name
Copy the code
// Rename individual variables
import { name, getName as getModName }
Copy the code

Module export

// The first way
export const name = 'Front Canteen'

Export function getName() {return name} export class Logger {log(... args) { console.log(... args) } }

Const name = 'front-end' function getName() {return name} class Logger {log(... args) { console.log(... args) } } export {name, getName, Logger}

Copy the code

// The fourth way const name = 'Front Canteen' export default name

Only some basic syntax is provided here, please refer to Ruan Yifeng’s Introduction to ECMAScript 6 for more syntax.

Of course, in different norms, the grammar to be regulated is also different. Airbnb, the recognized grammar norm in the industry, is recommended here.

Here are a few specifications for module export/import in Airbnb.

1. If the module has only one output value, use Export default. If the module has multiple output values, do not use Export default.

2. Do not use wildcards when importing modules. This ensures that you have an export default in your module.

// bad
import * as myObject from './importModule';
Copy the code

// good import myObject from './importModule';

ES Module vs. CommonJS

Import /export require/module

The 2.CommonJS module outputs a copy of the value (which does not change with the original value), while the ES6 module outputs a reference to the value (which changes with the original value).

The 3.CommonJS module is loaded at run time, and the ES6 module is the compile-time output interface.

Write in the last

People who constantly discuss the merits of this language or the evils of that language are even pathetic. Not only sad its blind, more sad its stupid complacent mentality. “– Avenue to Simplicity

JavaScrit still has some defects which are criticized by people. But history tells us that no amount of resistance can stop those who truly love it.

Thanks to the developers who contributed to the path of JavaScript modularity.

❤️ Love triple punch

1. Please click a “like” to support me when you see this. Your “like” is the motivation for my creation.

2. Pay attention to the public account “front-end canteen”, your front-end canteen, remember to eat on time!

3. Wear a mask for personal protection at special stage.