Introduction to CommonJS

The CommonJS module specification is a standard for processing modules in Node.js. Modules are very cool because they allow you to encapsulate various functions and expose that function as a library to other JavaScript files.

The CommonJS module specification is used toNode.jsUsed for modules.

Client-side JavaScript running in the browser uses another standard calledES module

Modules are very cool because they allow you to encapsulate various functions and expose that function as a library to other JavaScript files. They allow you to create reusable fragments with clear functionality, each of which can be tested individually.

hugenpmThe ecosystem is built based on this CommonJS format.

The syntax of the import module is:

const package = require('module-name')

In CommonJS, modules are loaded synchronously and processed in the order in which they are found when JavaScript is run. The system was originally designed with server-side JavaScript in mind, so it is not suitable for client-side applications (this is the reason for the introduction of ES modules).

A JavaScript file is a module when exporting one or more symbols (namely, variables, functions, and objects) defined by it:

uppercase.js

exports.uppercase = (str) => str.toUpperCase()

Any JavaScript file can import and use this module:

const uppercaseModule = require('uppercase.js')
uppercaseModule.uppercase('test')

A simple example can be foundIn this glitch.

You can export multiple values:

exports.a = 1
exports.b = 2
exports.c = 3

And useDestructive distribution:

const { a, b, c } = require('./uppercase.js')

Or just use the following method to export a value:

//file.js
module.exports = value

And use import

const value = require('./file.js')

Download mine for freeJavaScript beginner's manual


More js tutorials: