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

CommonJS模块导入ES模块dateformat报错,求解决方法

问题重现

Error [ERR_REQUIRE_ESM]: require() of ES Module ./node_modules/dateformat/lib/dateformat.js from ./channel_crawler_yt.js not supported.
Instead change the require of dateformat.js in ./channel_crawler_yt.js to a dynamic import() which is available in all CommonJS modules.


解决方案

方案1:在CommonJS脚本中使用动态import()

无需修改整体模块类型,直接替换require语句为异步导入:

  1. 找到脚本中导入dateformat的代码:
    const dateFormat = require('dateformat');
    
  2. 替换为以下两种方式之一:
    • async/await 写法(推荐,代码更清晰):
      将使用dateformat的逻辑包裹在async函数中:
      async function runCrawler() {
        const { default: dateFormat } = await import('dateformat');
        // 后续爬取逻辑,正常使用dateFormat即可
      }
      runCrawler();
      
    • Promise链式写法:
      不改动现有函数结构的情况下使用:
      import('dateformat').then(({ default: dateFormat }) => {
        // 这里编写原脚本中依赖dateFormat的代码
      });
      

方案2:将脚本转为ES模块

彻底切换到ES模块语法,适配dateformat的模块类型:

  1. 在项目根目录的package.json中添加字段:
    {
      "type": "module"
    }
    
  2. 将脚本中所有require()替换为ES模块的import语法:
    import dateFormat from 'dateformat';
    
    注意:如果脚本用到了CommonJS特有的__dirname/__filename,需要手动实现:
    import { fileURLToPath } from 'url';
    import { dirname } from 'path';
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:10:24