CommonJS 是一种用于 JavaScript 的模块化规范,主要应用于服务器端,尤其是在 Node.js 环境中广泛使用。它允许开发者将代码分割成多个文件,并通过模块的形式进行组织和复用。
module.exports
或 exports
对象将这些成员暴露给外部。require
函数引入并使用某个模块导出的成员。CommonJS 主要有两种类型的模块:
fs
(文件系统)、http
(HTTP 服务器)等。// math.js
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
module.exports = {
add,
subtract
};
// app.js
const math = require('./math');
console.log(math.add(2, 3)); // 输出: 5
console.log(math.subtract(5, 2)); // 输出: 3
原因:可能是路径错误或者模块未安装。
解决方法:
npm install <module-name>
原因:两个或多个模块相互依赖,导致无法正确加载。
解决方法:
require.main.require
来打破循环依赖。// moduleA.js
const moduleB = require('./moduleB');
module.exports = {
doSomething: () => {
moduleB.doSomethingElse();
}
};
// moduleB.js
const moduleA = require.main.require('./moduleA');
module.exports = {
doSomethingElse: () => {
moduleA.doSomething();
}
};
通过以上方法,可以有效解决 CommonJS 模块化过程中常见的问题。
没有搜到相关的文章