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

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

相关推荐
视图猿人6 小时前
RxJS基本使用及在next.js中使用的例子
开发语言·javascript
bitbitDown7 小时前
从零打造一个 Vite 脚手架工具:比你想象的简单多了
前端·javascript·面试
冴羽8 小时前
为什么在 JavaScript 中 NaN !== NaN?背后藏着 40 年的技术故事
前端·javascript·node.js
久爱@勿忘9 小时前
vue下载项目内静态文件
前端·javascript·vue.js
前端炒粉9 小时前
21.搜索二维矩阵 II
前端·javascript·算法·矩阵
不爱吃糖的程序媛9 小时前
Electron 应用中的系统检测方案对比
前端·javascript·electron
pe7er10 小时前
用高阶函数实现递归:从匿名函数到通用递归生成器
前端·javascript
IT古董10 小时前
全面理解 Corepack:Node.js 的包管理新时代
前端·node.js·corepack
Jonathan Star10 小时前
NestJS 是基于 Node.js 的渐进式后端框架,核心特点包括 **依赖注入、模块化架构、装饰器驱动、TypeScript 优先、与主流工具集成** 等
开发语言·javascript·node.js
学习3人组10 小时前
清晰地说明 NVM、NPM 和 NRM 在 Node.js 开发过程中的作用
前端·npm·node.js