Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hello, I’m Shanyue.

This is my front end engineering knowledge card collection 1/36 published in Nuggets

cjs (commonjs)

Commonjs is a Node module specification that imports and exports modules via require and exports. Module. Exports belong to Commonjs2.

Webpack also parses CJS modules, so CJS modules can run in node and WebPack environments, but not in browsers. But if you write the front end project in Webpack, you can also understand that it is supported in the browser and Node.

For example, the most popular 10 most downloaded modules in the world, ms, only support CommonJS, but it doesn’t affect its use in front-end projects (via Webpack), but if you want to introduce it directly into the browser via CDN, you might have a problem

// sum.js
exports.sum = (x, y) = > x + y

// index.js
const { sum } = require('./sum.js')
Copy the code

Since CJS is dynamically loaded, you can require a variable directly

require(`. /${a}`)
Copy the code

esm (es module)

Esm is a TC39 specification for JS modules, which can be imported and exported using export/import in Node and browser

// sum.js
export const sum = (x, y) = > x + y

// index.js
import { sum } from './sum'
Copy the code

Because ESM is statically imported, it is possible to Tree Shaking at the compiler, reducing JS size. Tc39 defines an API for dynamically loading modules: import(module).

Esm is the future trend. At present, some CDN manufacturers and front-end construction tools are committed to the transformation of CJS modules into ESM, such as Skypack, Snowpack, Vite, etc.

Esm is currently supported natively in both browsers and Node.js.

  • A CJS module outputs a copy of a value, while an ESM outputs a reference to a value
  • CJS modules are loaded at run time and ESM is loaded at compile time

Example: array – uniq

umd

A cJS-compatible and AMD-compatible module that can either be required in node/ Webpack environments or directly introduced by script.src in browsers using CDN

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD
    define(['jquery'], factory);
  } else if (typeof exports= = ='object') {
    // CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Global variables
    root.returnExports = factory(root.jQuery);
  }
}(this.function ($) {
  // ...
}));
Copy the code

Example: react-table, antd

The three module solutions are similar, but some NPM packages also package commonJS/ESM/UMD modular formats for different business needs