electron框架的自定义外部配置文件的配置与读取

您所在的位置:网站首页 electron读取文件 electron框架的自定义外部配置文件的配置与读取

electron框架的自定义外部配置文件的配置与读取

2024-06-03 06:52| 来源: 网络整理| 查看: 265

简介

在vue2.6版本后,会生成vue.config.js文件,本文章主要讲解如何在vue中,如何生成electron的外部配置文件,与如何读取外部配置文件。

一、配置与生成config.json文件

首先,要在项目下新建一个config.json文件,然后再config文件中,写入一些信息。 在这里插入图片描述 然后在vue.config.js中写入配置,通知electron在打包时,不要将指定文件打包进app.asar中。

pluginOptions: { electronBuilder: { builderOptions: { // build配置在此处 // options placed here will be merged with default configuration and passed to electron-builder appId: "com.emr.app", extraResources: [ { "from": "./config.json", "to": "../" } ], "mac": { "icon": "./public/favicon.icns" }, "win": { "icon": "./public/favicon.ico" } // 配置打包后,在win下的应用图标。ico图片至少要是256*256尺寸的,尺寸太小,会打包失败。 } }, },

这里附上我的vue.config.js文件的配置,方便大家理解

const webpack = require('webpack') module.exports = { lintOnSave: false, publicPath: "./", // PC端适配代码 // css: { // loaderOptions: { // css: {}, // postcss: { // plugins: [ // require("postcss-px2rem")({ // remUnit: 192, // 以1920屏幕为标准来缩放网页 // propList: ['*', '!border', '!font-size'], // border属性不进行适配 // }) // ] // } // } // }, chainWebpack: config => { config.plugin('provide').use(webpack.ProvidePlugin, [{ $: 'jquery', jquery: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' }]) }, configureWebpack: { resolve: { alias: {} } }, pluginOptions: { electronBuilder: { builderOptions: { // build配置在此处 // options placed here will be merged with default configuration and passed to electron-builder appId: "com.emr.app", extraResources: [ { "from": "./config.json", "to": "../" }, { "from": "./MatchDownloader.exe", "to": "../" }, { "from": "./download.bat", "to": "../" }, ], "mac": { "icon": "./public/favicon.icns" }, "win": { "icon": "./public/favicon.ico" } } }, }, // 代理 /* devServer: { port: 8080, // host: 'localhost', https: false, // https:{type:Boolean} open: true, // 配置自动启动浏览器 disableHostCheck: true, "proxy": { "/*": { "target": "http://xxx", "changeOrigin": true } } }, */ } 然后,在执行npm run electron:build命令后,就可以在打包后的文件里看到config.json文件被独立出来了。

在这里插入图片描述 至此,就完成了第一步,配置与生成config.json这个外部配置文件了。

二、读取外部配置文件 ---- config.json

至此,我们已经有了config.json这个外部配置文件,要读取这个文件的配置信息,就要用到electron的remote模块,这个模块不同electron版本的获取方式不同,这个用了是electron13.0.0的获取方法。

首先,要在electorn的入口文件(我项目里的是background.js)里,做一些配置,让html页面能访问node里面的fs模块,方便调用fs来读取文件。

// main.js 'use strict' // Modules to control application life and create native browser window // const { app, BrowserWindow } = require('electron') import moment from "moment" import { app, protocol, BrowserWindow, globalShortcut } from 'electron' import { createProtocol, installVueDevtools } from 'vue-cli-plugin-electron-builder/lib' // 设置运行内存350MB process.env.NODE_OPTIONS = '--no-warnings --max-old-space-size=350' // app.commandLine.appendSwitch('disable-site-isolation-trials'); // //这行一定是要加的,要不然无法使用iframe.contentDocument方法 const { ipcMain, Menu, MenuItem, shell } = require('electron') const path = require('path') const fs = require('fs') const exePath = path.dirname(app.getPath('exe')) const localFileUrlList = { // 要生成的文件的本地文件路劲 'app.asar': { win: '\\resources\\app.asar', mac: '/resources/app.asar' }, 'update.asar': { win: '\\resources\\update.asar', mac: '/resources/update.asar' }, 'download.bat': { win: '\\download.bat', mac: '/download.bat' } } // console.log("exePath", exePath) const menuContextTemplate = [ { label: '复制', role: 'copy' }, // 使用了role,click事件不起作用 { label: '粘贴', role: 'paste' } ] const menuBuilder = Menu.buildFromTemplate(menuContextTemplate) // Scheme must be registered before the app is ready protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }]) function showGoBackMenu (mainWindow) { const template = [{ label: '返回', submenu: [{ label: '返回上一页', click: () => { mainWindow.webContents.goBack() } }] }, { label: '刷新', // 重新加载代码 accelerator: 'CmdOrCtrl+R', click: function (item, focusedWindow) { if (focusedWindow) { focusedWindow.reload() } } } ] // 构建菜单模版 const m = Menu.buildFromTemplate(template) // 设置菜单模版 Menu.setApplicationMenu(m) } function deleteOldLogFiles() { let rententionPeriodInMs = 7 * 24 * 60 * 60 * 1000 let now = new Date().getTime() // 时间阈值,创建时间早于此阈值,则删除对应文件 let thresholdTime = now - rententionPeriodInMs let LogsFolderPath = path.join(exePath, "logs") console.log("LogsFolderPath", LogsFolderPath) let files = fs.readdirSync(LogsFolderPath) files.forEach(file => { let filePath = path.join(LogsFolderPath, file) let fileStat = fs.statSync(filePath) // 返回文件的文件信息 let createTimeOfFile = fileStat.ctimeMs // 获取文件的创建时间 if (createTimeOfFile // Create the browser window. const mainWindow = new BrowserWindow({ width: 800, height: 600, title: '', webPreferences: { // preload: path.join(__dirname, 'preload.js'), nodeIntegration: true, // 允许html页面上的javascipt代码访问nodejs 环境api代码的能力 enableRemoteModule: true, // 是否允许使用remote contextIsolation: false, // 加载本地图片 webSecurity: false, // 允许跨域 webviewTag: true // 允许webview }, icon: path.join(__static, './favicon.ico'), show: false, autoHideMenuBar: true, // 隐藏顶部工具栏,生产环境时设置为true frame: false // 无边框 }) let timeStr = moment(new Date()).format("YYYY-MM-DD HH:mm:ss") let dateStr = moment(new Date()).format("YYYY-MM-DD") let LogsFolderPath = path.join(exePath, "logs") let logFilePath = path.join(LogsFolderPath, `log-${dateStr}.log`) // 如果文件夹不存在,则新建 if (!fs.existsSync(LogsFolderPath)) { fs.mkdirSync(LogsFolderPath) } // 删除7天前的日志文件,节约硬盘空间 deleteOldLogFiles() // 监听控制台错误输出的事件 mainWindow.webContents.on('console-message', (event, level, message, line, sourceId) => { if (level === 3) { // 3 代表错误级别 const logMessage = `[${timeStr}] ${message}\n`; fs.appendFileSync(logFilePath, logMessage); console.error(logMessage); } }); // 生产环境下隐藏此函数 // showGoBackMenu(mainWindow) globalShortcut.register('CommandOrControl+Shift+i', function () { mainWindow.webContents.openDevTools() }) mainWindow.maximize() mainWindow.show() createProtocol('app') mainWindow.loadURL('http://localhost:8080') // 跑本地开启这行,打包的时候注掉这行 // mainWindow.loadURL(`app://./index.html`); //打包的时候开启这行,跑本地注掉这行 // 1. 窗口 最小化 ipcMain.on('window-min', function () { // 收到渲染进程的窗口最小化操作的通知,并调用窗口最小化函数,执行该操作 mainWindow.minimize() }) // 2. 窗口 最大化、恢复 ipcMain.on('window-max', function () { if (mainWindow.isMaximized()) { // 为true表示窗口已最大化 mainWindow.restore() // 将窗口恢复为之前的状态. } else { mainWindow.maximize() } }) // 3. 关闭窗口 ipcMain.on('window-close', function () { mainWindow.close() }) // 刷新窗口 ipcMain.on('window-reload', function () { // 收到渲染进程的窗口最小化操作的通知,并调用窗口最小化函数,执行该操作 mainWindow.reload() }) ipcMain.on('show-context-menu', function () { menuBuilder.popup({ window: BrowserWindow.getFocusedWindow() }) }) ipcMain.on('print-view', function () { const win = new BrowserWindow({ width: 800, height: 600 }) // 打开新窗口 BrosweWindow 初始化 win.loadURL('http://www.baidu.com') win.webContents.printToPDF({ pageSize: 'A4', printBackground: true }, (error, data) => { console.log('---------------------------------:', data) if (error) throw error debugger fs.writeFile('print.pdf', data, (error) => { if (error) throw error console.log('Write PDF successfully.') }) }) }) // json: { downloadUrl: "", targetPath: "C:\\...", fileName: "config.json" } ipcMain.on('system-update', function (event, { json, asar }) { console.log('system-update', asar) const request = require('request') const req = request({ method: 'GET', uri: json.downloadUrl }) const out = fs.createWriteStream(json.targetPath) req.pipe(out) req.on('end', function () { const batPath = getFilePath('download.bat') // console.log("batPath", batPath) const fileData = `MatchDownloader.exe /opt url ${asar.downloadUrl} process Match-EMR.exe src ~/resources/update.asar dest ~/resources/app.asar` fs.writeFileSync(batPath, fileData) shell.openPath(batPath) // 打开bat文件 app.quit() // 关闭应用 }) }) } app.whenReady().then(async () => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // 除了 macOS 外,当所有窗口都被关闭的时候退出程序。 There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit() }) function getFilePath (localFileName) { console.log('localFileName', localFileName) if (getSystem() === 1) { return exePath + localFileUrlList[localFileName].mac } else { return exePath + localFileUrlList[localFileName].win } } function getSystem () { // 这是mac系统 if (process.platform == 'darwin') { return 1 } // 这是windows系统 if (process.platform == 'win32') { return 2 } // 这是linux系统 if (process.platform == 'linux') { return 3 } }

关键配置就在102行附近,createWindow函数的new BrowserWindow里,nodeIntegration: true和enableRemoteModule: true。这2个配置,一个是允许页面支持node环境及其api调用。一个允许页面使用remote对象。

其次,新建一个getBaseUrl.js文件

const path = window.require && window.require("path"); const fs = window.require && window.require("fs"); const electron = window.require && window.require('electron') export function getSystem() { //这是mac系统 if (process.platform == "darwin") { return 1; } //这是windows系统 if (process.platform == "win32") { return 2; } //这是linux系统 if (process.platform == "linux") { return 3; } } /** * * @returns 获取安装路径 */ export function getExePath() { // return path.dirname("C:"); return path.dirname(electron.remote.app.getPath("exe")); } /** * * @returns 获取配置文件路径 */ export function getConfigPath() { if (getSystem() === 1) { return getExePath() + "/config.json"; } else { return getExePath() + "\\config.json"; } } /** * 读取配置文件 */ export function readConfig() { return new Promise((res, rej) => { console.log("fs", fs) fs.readFile(getConfigPath(), "utf-8", (err, data) => { let config = "" if (data) { //有值 config = JSON.parse(data) } res(config) }) }) }

这个文件的readConfig函数,就是获取config文件的函数。所以外部只要调用这个readConfig函数,就可以获取外部配置文件的信息了(你可以在main.js里调用,就是在项目加载时,就读取config.json这个配置文件)。

例如:

import { readConfig } from '@/utils/getBaseUrl.js' // let applicationType = 'website' // 如果最后打包的是网站,就打开这个 let applicationType = "exe" // 如果最后打包的是exe应用,就打开这个 if (applicationType === 'exe') { (async function () { const res = await readConfig() axios.defaults.baseURL = res.baseUrl Vue.prototype.$baseURL = res.baseUrl window.$config = res })() } // 因为我原来的项目是可以打包成网站与桌面应用,但是在网页版中,window.require('electron')返回的是undefined,所以这里才会用applicationType来区分,如果打包后的是exe应用时,才去读取安装目录下的config.json文件 最后

这篇文章就讲这个外部配置文件的生成与获取,如果大家有兴趣的话,会找个时间分享一下,electron的桌面的版本更新下载的功能,就像其他桌面应用一样,点击更新按钮,自动下载与更新应用的功能。 附上我当前项目的vue与electron版本

"vue": "^2.6.11", "electron": "^13.0.0", "electron-packager": "^15.4.0",

这就是这篇文章的主要内容了,如果这篇文章对你有帮助,记得留下你的点赞了,谢谢啦~~



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3