配置文件

一般web前端项目配置文件,写死的放在src/config下,需要打包配置的放在.env文件中。但在electron项目中,如果配置数据更改,需要每次给用户打包升级肯定是行不通的。于是外部配置文件就是有必要的,具体实现方法也比较简单,通过fs去读写外部文件就可实现

具体实现

设置文件不被压缩混淆

将配置文件放在根目录的config文件夹
配置electron- builder文件,我这里是yml配置

...
productName: xxx
asarUnpack:
  - resources/**
extraResources:
  - ./config
...

extraResources属性添加文件夹名称
打包后路径为/resources/config/...可以打包后查看

获取路径

process.cwd()
此时获取是node服务的根路径,再拼接上本地文件的路径
dev环境为项目根目录
prod环境为安装后文件夹路径

const path = process.cwd()
const filePath = is.dev
  ? join(path, '/config/app.properties')
  : join(path, '/resources/config/app.properties')

读写文件

这里用到了fspathini等node模块,所以不可以在renderer里面操作,要通过主进程handle通信到渲染进程获取

npm i ini

class ConfigHandle {
  private getConfig(_: IpcMainInvokeEvent) {
    return new Promise((resolve, reject) => {
      fs.readFile(filePath, 'utf8', function (err, dataStr) {
        if (err) {
          return reject(err.message)
        }
        resolve(ini.parse(dataStr.toString()))
      })
    })
  }

  private setConfig(_: IpcMainInvokeEvent, config) {
    return new Promise((resolve, reject) => {
      fs.readFile(filePath, 'utf8', function (err, dataStr) {
        if (err) {
          return reject(err.message)
        }
        const origin = ini.parse(dataStr.toString())
        // 这里做了先读取再assign操作,不会全量覆盖
        fs.writeFile(filePath, ini.stringify(Object.assign(origin, config)), function (err) {
          if (err) {
            return reject(err.message)
          }
          resolve('success')
        })
      })
    })
  }

  register() {
    ipcMain.handle('get-config', this.getConfig)
    ipcMain.handle('set-config', this.setConfig)
  }
}

通信到renderer

  • main
configHandle.register()
  • preload
const api = {
  config: {
    get: () => ipcRenderer.invoke('get-config'),
    set: (config: object) => ipcRenderer.invoke('set-config', config)
  }
}

contextBridge.exposeInMainWorld('api', api)
  • renderer
export const config = await window.api.config.get()
export const setConfig = config => window.api.config.set(config)


const baseUrl = config.baseUrl

setConfig({baseUrl: "http://xxx"})

这样可以通过程序修改配置文件,或者用户自己编辑修改配置文件

  • config/app.properties
title=good title
baseUrl=great url
defaultPassword=unbelievable pwd

通过ini.parse会转成json格式,非常方便

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。