CommonJS简介

CommonJS简介

Tags: JavaScript, Node.js, commonjs
Published: 2023/09/26

什么是commonjs

commonjs是module的一种类型(规范)

使用场景

CommonJS is mainly used in server-side JS apps with Node, as browsers don’t support the use of CommonJS.

CommonJS 主要用于带有 Node 的服务器端 JS 应用程序,因为浏览器不支持使用 CommonJS。

如何使用

package.json

The “type” field defines the module format that Node.js uses for all .js files that have that package.json file as their nearest parent.

"type" 字段定义 Node.js 用于所有将该 package.json 文件作为其最近父级的 .js 文件的模块格式。

在package中不需要显示定义type(type的可选项是commonjs和module),一般是需要用到ESM的时候才去定义module。

package的影响范围是当前文件夹以及子文件夹的所有js文件。(ts会被ts编译器转化为js代码)

语法

导入:require
导出:module.exports

举个例子:

// 导出两个函数
exports.add = function(a, b) {
  return a + b;
};

exports.multiply = function(a, b) {
  return a * b;
};

// 引入 math 模块
var math = require('./math');

// 使用 math 模块中的函数
var sum = math.add(5, 3);
var product = math.multiply(4, 6);

console.log('Sum:', sum);
console.log('Product:', product);


批量导入导出:

// 定义多个实用函数
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

// 将这些函数添加到一个对象中并导出该对象
module.exports = {
  add,
  subtract
};

// main.js

// 引入 utils 模块
var utils = require('./utils');

// 使用 utils 模块中的函数
var sum = utils.add(5, 3);
var difference = utils.subtract(8, 2);

console.log('Sum:', sum);
console.log('Difference:', difference);

参考:

Modules: Packages | Node.js v20.7.0 Documentation

Modules in JavaScript – CommonJS and ESmodules Explained

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值