记录:Error [ERR_REQUIRE_ESM]: require() of ES Module not supported.报错

记录:在js中导入jsencrypt模块时,出现Error ERR_REQUIRE_ESM: require() of ES Module xxxxx from xxxxx not supported.报错

代码:

javascript 复制代码
const JSEncrypt = require("jsencrypt")

报错:

javascript 复制代码
const JSEncrypt = require("jsencrypt")
                  ^

Error [ERR_REQUIRE_ESM]: require() of ES Module D:\yj_pj\node_modules\jsencrypt\bin\jsencrypt.js from D:\yj_pj\YWF\test123\wenshu.js not supported.
jsencrypt.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead rename jsencrypt.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in D:\yj_pj\no
de_modules\jsencrypt\package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

    at Object.<anonymous> (D:\yj_pj\YWF\test123\wenshu.js:3:19) {
  code: 'ERR_REQUIRE_ESM'
}

解决办法:

将提示语翻译过来:

将jsencrypt.js重命名为以.cjs结尾,将所需代码更改为使用所有CommonJS模块中可用的dynamicimport(),或将D:\yj_pj\no中的"type":"module"更改为"type""CommonJS"

de_modules\jsencrypt\package.json将所有.js文件视为CommonJS(将.mjs用于所有ES模块)。

  1. 按照提示语将jsencrypt.js 重命名为 jsencrypt.cjs
  1. 将上一级目录中的package.json 下的 main 值同步修改为刚刚重命名的文件,

即"main": "bin/jsencrypt.js", --->> "main": "bin/jsencrypt.cjs",

修改好后再次回到我们写的文件中运行发现,可以正常运行了

相关推荐
flyinmind4 小时前
Java环境与Android环境中使用QuickJS
java·开发语言·javascript·quickjs
如烟花的信页4 小时前
数美滑块逆向分析
javascript·爬虫·python·js逆向
子琦啊4 小时前
华为 OD 2026年5月笔试题解析
javascript·华为
无风听海4 小时前
Promise 与 Async Await 深度解析
前端·javascript
很楠爱上4 小时前
Node.js 模块化学习笔记
笔记·学习·node.js
linksinke5 小时前
Node.js 版本管理管理器的使用注意 - NVM
node.js·nvm·node多版本·node切换
橘子味的冰淇淋~5 小时前
优化前端性能之从“全局引入”改为“按需引入”
前端·javascript·vue.js
Wonderful U5 小时前
基于Python爬虫+Django的轻量化天气预报系统:从数据抓取到可视化展示的完整实战
爬虫·python·django
Vennn5 小时前
Android自动化:使用 Web 方式实现某音未读消息检查与采集
前端·javascript·vue.js
Smilezyl5 小时前
为了搞懂 AI Agent,我用 6000 行 JS 代码手搓了一个零依赖的 Coding Agent
前端·javascript·github