记录: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",

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

相关推荐
前端小趴菜0520 分钟前
React-React.memo-props比较机制
前端·javascript·react.js
RadiumAg3 小时前
记一道有趣的面试题
前端·javascript
yangzhi_emo3 小时前
ES6笔记2
开发语言·前端·javascript
yanlele3 小时前
我用爬虫抓取了 25 年 5 月掘金热门面试文章
前端·javascript·面试
烛阴5 小时前
void 0 的奥秘:解锁 JavaScript 中 undefined 的正确打开方式
前端·javascript
初遇你时动了情5 小时前
腾讯地图 vue3 使用 封装 地图组件
javascript·vue.js·腾讯地图
dssxyz5 小时前
uniapp打包微信小程序主包过大问题_uniapp 微信小程序时主包太大和vendor.js过大
javascript·微信小程序·uni-app
ohMyGod_1237 小时前
React16,17,18,19新特性更新对比
前端·javascript·react.js
@大迁世界7 小时前
第1章 React组件开发基础
前端·javascript·react.js·前端框架·ecmascript
一瓣橙子7 小时前
7.7日 实验03-Spark批处理开发(2)
开发语言·javascript·ajax