Electron+Vite+Vue3开发环境读取自定义txt文件失败求助
解决Electron开发环境下custom-resources文件读取失败的问题
问题根源
开发环境下__dirname的指向取决于代码所在目录(比如src/main或src/renderer),之前的路径拼接方式会错误指向Electron内置的asar包目录,而非项目根目录下的custom-resources。
解决方案
直接通过项目根目录定位资源文件夹,同时用Electron原生的app.isPackaged判断环境(比自定义IS_DEV更可靠):
主进程中使用的代码
import path from 'path' import { app } from 'electron' // 获取资源目录的绝对路径 export const getResourcesDirPath = () => { if (!app.isPackaged) { // 开发环境:直接指向项目根目录下的custom-resources return path.resolve(process.cwd(), 'custom-resources') } else { // 生产环境:拼接Electron的resources路径 return path.join(process.resourcesPath, 'custom-resources') } } // 生成目标文件的绝对路径 export const getFile = (file: string) => { return path.join(getResourcesDirPath(), file) }
渲染进程中使用(符合上下文隔离规范)
如果需要在渲染进程中获取文件路径,建议通过主进程暴露API:
// 主进程代码 import { contextBridge } from 'electron' import path from 'path' import { app } from 'electron' const getResourcesDirPath = () => { if (!app.isPackaged) { return path.resolve(process.cwd(), 'custom-resources') } else { return path.join(process.resourcesPath, 'custom-resources') } } // 向渲染进程暴露安全API contextBridge.exposeInMainWorld('electronResources', { getFile: (file: string) => path.join(getResourcesDirPath(), file) })
渲染进程中调用:
const filePath = window.electronResources.getFile('test.txt') // 后续读取文件逻辑
关键说明
process.cwd():开发环境下返回启动Electron时的工作目录,也就是项目根目录,能直接定位到custom-resources。app.isPackaged:Electron原生提供的环境判断,打包后为true,开发时为false,避免自定义环境变量的错误。
内容的提问来源于stack exchange,提问作者major697
相关产品推荐
相关产品推荐

