错误描述
vue3-element-admin 项目将Vite4 升级至 Vite5 后,项目运行出现如下警告:
The CJS build of Vite's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.
图片
问题原因
Vite 官方弃用 CJS 说明,参考文档 deprecate-cjs-node-api 。
图片
解决方案
Vite 官方 Github 仓库下的 ISSUE:“ The CJS build of Vite’s Node API is deprecated” when using a TS vite.config.ts and the package.json has no type
图片
根据官方说明文档和 ISSUE 下的解决方案有两种:
解决方案一
在package.json 添加 "type": "module"
默认情况下 Node.js 默认将 .js 文件作为 CommonJS (CJS) 模块来处理。
当将 “type”: “module” 添加到 package.json 中,Node.js 会将 .js 文件作为 ECMAScript Modules (ESM) 来处理。
解决方案二
将 vite.config.ts 文件改名为 vite.config.mts
文件扩展名 .mts 明确地指示 Node.js 将该文件作为一个 ECMAScript Module (ESM) 来处理。
这与在 package.json 中设置 “type”: “module” 相类似,都是为了确保 Node.js 以 ESM 格式解析和执行模块。