【开发心得】Electron(Vue)使用配置文件

背景: Vue+ElementUI的web项目中, 可以配置一个config.js来解决,那么eletron呢?

思路有两个:

1. 直接使用  global.sharedObject 让main线程与render线程直接数据共享。

2. 借助事件传递。

项目根路径直接放置一个配置文件,可以是config.json 或者 config.yml,都有对应的处理方案,这里以config.yaml做例子:

注意:使用yml的话记得 : yarn add yamljs

src/main/index.js (或者main.js)的代码片段如下:

import fs from 'fs';
import logger from './logger';
const path = require('path');
const YAML = require('yamljs');
// 读取配置文件
// process.cwd() 读取到打包后的根目录
// const configPath = path.join(process.cwd(), 'config.yml');

const configPath = process.env.NODE_ENV === 'development' ? path.join(__dirname, '../../config.yml') : path.join(process.cwd(), 'config.yml');
logger.log(`config path:${configPath}`);
const configData = fs.readFileSync(configPath, 'utf-8');
const configJson = YAML.parse(configData);
logger.log(`init config: ${JSON.stringify(configJson)}`);

global.sharedObject = {
  config: { // 存放配置文件数据
    ...configJson,
  },
};

render线程使用:

// eslint-disable-next-line prefer-destructuring
const remote = require('electron').remote;
// eslint-disable-next-line prefer-destructuring
const waterMarkTreeNodeConf = remote.getGlobal('sharedObject').config.xxxx;

package.json build设置(省略其它配置)

  "build": {
    "extraResources":  {
      "from": "./config.yml",
      "to": "../"
    }
  },

这样就实现了配置文件。如果需要热刷新,就使用事件监听方式,在main线程中,监听下,render线程在需要配置的时候,去请求一下。

posted @ 2022-08-11 19:19  虹梦未来  阅读(1)  评论(0编辑  收藏  举报  来源