一、问题描述
Vite版本:4.0.1 升级到 4.2.1
项目环境相关(本地开发环境):Electron+vite+vue
运行命令: yarn dev
警告信息:
browser-external:path:9 Module "path" has been externalized for browser compatibility.
Cannot access "path.join" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
错误栈信息:
Uncaught TypeError: path.join is not a function
at node_modules/electron/index.js (index.js:4:23)
at __require (chunk-DFKQJ226.js?v=bfbad5a0:8:50)
at node_modules/@electron/remote/dist/src/common/type-utils.js (type-utils.js:4:20)
at __require (chunk-DFKQJ226.js?v=bfbad5a0:8:50)
at node_modules/@electron/remote/dist/src/renderer/remote.js (remote.js:5:22)
at __require (chunk-DFKQJ226.js?v=bfbad5a0:8:50)
at node_modules/@electron/remote/dist/src/renderer/index.js (index.js:15:14)
at __require (chunk-DFKQJ226.js?v=bfbad5a0:8:50)
at node_modules/@electron/remote/renderer/index.js (index.js:1:18)
at __require (chunk-DFKQJ226.js?v=bfbad5a0:8:50)
二、原因调查
vite 升级后已不支持在客户端代码中访问内置模块代码。
过程分析:
http://localhost:5566/node_modules/.vite/deps/@electron_remote.js?v=bfbad5a0
node_modules/.vite/deps/
:项目中所需要的依赖,vite调用 esbuild (对js语法进行处理的一个库),将其他规范的代码转换成esmodule规范;然后放到该文件夹下;同时对esmodule规范的各个模块进行统一集成。
因此,@electron_remote.js实际就是项目依赖的@electron/remote模块。
在Electron应用中import @electron/remote模块,该模块中会 require("electron")
,从而执行了path、fs等Node内置模块代码,而Vite 4.2.1对此已不支持(不做转换):
而Vite 4.0.1则做了转换:
三、解决方案
在vite.config.js中:
import optimizer from 'vite-plugin-optimizer'
export default defineConfig({
plugins: [
optimizer({
electron: `const { ipcRenderer } = require('electron'); export { ipcRenderer };`
}),
...
]
})