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语句为异步导入:
- 找到脚本中导入dateformat的代码:
const dateFormat = require('dateformat'); - 替换为以下两种方式之一:
- async/await 写法(推荐,代码更清晰):
将使用dateformat的逻辑包裹在async函数中:async function runCrawler() { const { default: dateFormat } = await import('dateformat'); // 后续爬取逻辑,正常使用dateFormat即可 } runCrawler(); - Promise链式写法:
不改动现有函数结构的情况下使用:import('dateformat').then(({ default: dateFormat }) => { // 这里编写原脚本中依赖dateFormat的代码 });
- async/await 写法(推荐,代码更清晰):
方案2:将脚本转为ES模块
彻底切换到ES模块语法,适配dateformat的模块类型:
- 在项目根目录的
package.json中添加字段:{ "type": "module" } - 将脚本中所有
require()替换为ES模块的import语法:
注意:如果脚本用到了CommonJS特有的import dateFormat from 'dateformat';__dirname/__filename,需要手动实现:import { fileURLToPath } from 'url'; import { dirname } from 'path'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename);
内容的提问来源于stack exchange,提问作者KyleSforza
相关产品推荐
相关产品推荐

