commonjs_CommonJS简介

commonjs

The CommonJS module specification is the standard used in Node.js for working with modules.

CommonJS模块规范是Node.js中用于处理模块的标准。

Client-side JavaScript that runs in the browser uses another standard, called ES Modules

在浏览器中运行的客户端JavaScript使用另一种称为ES模块的标准

Modules are very cool, because they let you encapsulate all sorts of functionality, and expose this functionality to other JavaScript files, as libraries. They let you create clearly separate and reusable snippets of functionality, each testable on its own.

模块非常酷,因为它们使您可以封装各种功能,并将该功能作为库公开给其他JavaScript文件。 它们使您可以创建清晰独立且可重复使用的功能片段,每个片段均可独立测试。

The huge npm ecosystem is built upon this CommonJS format.

巨大的npm生态系统基于此CommonJS格式构建。

The syntax to import a module is:

导入模块的语法为:

const package = require('module-name')

In CommonJS, modules are loaded synchronously, and processed in the order the JavaScript runtime finds them. This system was born with server-side JavaScript in mind, and is not suitable for the client-side (this is why ES Modules were introduced).

在CommonJS中,模块是同步加载的,并按照JavaScript运行时找到它们的顺序进行处理。 该系统最初是考虑到服务器端JavaScript的,因此不适用于客户端(这就是引入ES模块的原因)。

A JavaScript file is a module when it exports one or more of the symbols it defines, being them variables, functions, objects:

JavaScript文件在导出其定义的一个或多个符号(即变量,函数和对象)时是一个模块:

uppercase.js

uppercase.js

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

Any JavaScript file can import and use this module:

任何JavaScript文件都可以导入和使用此模块:

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

A simple example can be found in this Glitch.

在此故障中可以找到一个简单的示例。

You can export more than one value:

您可以导出多个值:

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

and import them individually using the destructuring assignment:

并使用解构任务分别导入它们:

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

or just export one value using:

或仅使用以下方法导出一个值:

//file.js
module.exports = value

and import it using

并使用导入

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

翻译自: https://flaviocopes.com/commonjs/

commonjs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值