基于Egg框架的Node.js v14应用如何兼容纯ESM版p-debounce及type:module配置说明
基础开发环境与需求
- 运行环境:Node.js v14.15.4,基于Egg框架搭建的应用
- 核心目标:接入最新版本的
p-debounce库 - 已知版本特性:
p-debounce从v3.0.0版本起为纯ESM格式,原有的const pDebounce = require('p-debounce')CommonJS导入写法不再适用,需改用import pDebounce from 'p-debounce'的ESM语法,但该写法在当前Egg.js环境下无法正常运行。
直接使用import写法的报错
(node:10636) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. (Use `node --trace-warnings ...` to show where the warning was created) test.js:5 import pDebounce from 'p-debounce' ^^^^^^ SyntaxError: Cannot use import statement outside a module
尝试使用require写法的报错
internal/modules/cjs/loader.js:1080 throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath); ^ Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: .\node_modules\p-debounce\index.js require() of ES modules is not supported. require() of .\node_modules\p-debounce\index.js from .\test.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from .\node_modules\p-debounce\package.json.
给项目自身package.json添加"type": "module"后的报错
const path = require('path'); ^ ReferenceError: require is not defined
项目现状与待解决问题
当前项目内存在大量require写法的CommonJS代码,暂时不具备全量迁移为import语法的条件,需要解决两个核心问题:
- package.json中的
"type": "module"配置项是什么含义? - 如何在不批量修改现有CommonJS代码的前提下,解决上述兼容报错?
内容的提问来源于stack exchange,提问作者A.A
相关产品推荐
相关产品推荐

