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

如何在Node.js运行时判断代码是CommonJS还是ESM模块?

运行时检测CommonJS与ESM模块系统的方法

当然可以在运行时检测当前所处的模块系统,核心是利用两种模块体系的特有标识来区分:

  • CommonJS环境特征:模块内会存在require函数、module对象以及module.exports导出接口
  • ESM环境特征:模块内会存在import.meta元数据对象(这是ESM标准内置的专属属性)

实用检测函数

function getModuleSystemType() {
  // 判定CommonJS环境
  if (typeof require === 'function' && typeof module !== 'undefined' && module.exports) {
    return 'CommonJS';
  }
  // 判定ESM环境
  if (typeof import.meta !== 'undefined') {
    return 'ESM';
  }
  // 无法识别的环境
  return 'Unknown';
}

跨模块系统适配示例

拿到模块系统类型后,就能针对性执行不同逻辑:

// 跨模块系统兼容的工具函数
function crossEnvUtility() {
  const moduleType = getModuleSystemType();

  if (moduleType === 'CommonJS') {
    // CommonJS专属逻辑:同步加载依赖,用module.exports导出
    const path = require('path');
    module.exports = {
      resolvePath: (p) => path.resolve(__dirname, p)
    };
  } else if (moduleType === 'ESM') {
    // ESM专属逻辑:可使用静态import或动态import(),用export导出
    import('path').then((path) => {
      // 异步加载依赖后的逻辑
    });
    export const resolvePath = (p) => new URL(p, import.meta.url).pathname;
  }
}

注意事项

  • 不要依赖process对象判断:部分CommonJS环境(如打包后的浏览器环境)可能没有process,而Node.js的ESM环境也会存在process,这个标识并不可靠
  • 转译工具影响:如果用Babel、TypeScript等工具转译模块,可能会抹平原生模块系统的差异,此时检测逻辑需要结合转译配置调整

内容的提问来源于stack exchange,提问作者ChrisNY

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:42:09