You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计JS自定义模块导入、导出的函数数量?

Node.js 统计自定义模块导入函数数量的方法

你要统计示例中new.js导入的函数总数,本质是统计对应自定义模块导出对象中值为函数的可枚举属性总数,具体实现方式如下:

方法1:导入完整模块对象后统计(可统计模块导出的所有函数)

先通过require拿到完整的模块导出对象,再遍历筛选出所有类型为函数的属性,统计总数即可:

// new.js
const myModule = require('./module');

// 写法1:循环遍历统计
let functionCount = 0;
for (const key in myModule) {
  if (typeof myModule[key] === 'function') {
    functionCount++;
  }
}
console.log(functionCount); // 示例中输出2

// 写法2:更简洁的链式调用
const functionCount = Object.values(myModule).filter(item => typeof item === 'function').length;
console.log(functionCount); // 示例中输出2

该方法会自动过滤导出对象中的非函数属性,统计结果为模块导出的所有函数总数。

方法2:统计已解构导入的函数数量

如果你已经使用解构赋值显式导入了部分函数,只想统计当前已导入的函数数量,可以直接统计解构变量中函数的数量:

// new.js
const {add, sub} = require('./module');

const importFunctionCount = [add, sub].filter(item => typeof item === 'function').length;
console.log(importFunctionCount); // 示例中输出2

注意该方法只能统计你显式解构出来的项,无法覆盖模块导出的所有未被解构的函数。

内容的提问来源于stack exchange,提问作者Gourav Singh Rawat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:15:00