簡介
在vue2.6版本后,會生成vue.config.js文件,本文章主要講解如何在vue中,如何生成electron的外部配置文件,與如何讀取外部配置文件。
一、配置與生成config.json文件
首先,要在項目下新建一個config.json文件,然后再config文件中,寫入一些信息。
然后在vue.config.js中寫入配置,通知electron在打包時,不要將指定文件打包進(jìn)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下的應(yīng)用圖標(biāo)。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屏幕為標(biāo)準(zhǔn)來縮放網(wǎng)頁
// propList: ['*', '!border', '!font-size'], // border屬性不進(jìn)行適配
// })
// ]
// }
// }
// },
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
}
}
}, */
}
然后,在執(zhí)行npm run electron:build命令后,就可以在打包后的文件里看到config.json文件被獨立出來了。
至此,就完成了第一步,配置與生成config.json這個外部配置文件了。
二、讀取外部配置文件 ---- config.json
至此,我們已經(jīng)有了config.json這個外部配置文件,要讀取這個文件的配置信息,就要用到electron的remote模塊,這個模塊不同electron版本的獲取方式不同,這個用了是electron13.0.0的獲取方法。
首先,要在electorn的入口文件(我項目里的是background.js)里,做一些配置,讓html頁面能訪問node里面的fs模塊,方便調(diào)用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'
// 設(shè)置運行內(nèi)存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: '復(fù)制', 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()
}
}
}
]
// 構(gòu)建菜單模版
const m = Menu.buildFromTemplate(template)
// 設(shè)置菜單模版
Menu.setApplicationMenu(m)
}
function deleteOldLogFiles() {
let rententionPeriodInMs = 7 * 24 * 60 * 60 * 1000
let now = new Date().getTime()
// 時間閾值,創(chuàng)建時間早于此閾值,則刪除對應(yīng)文件
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 // 獲取文件的創(chuàng)建時間
if (createTimeOfFile < thresholdTime) {
fs.unlinkSync(filePath)
}
})
}
const createWindow = () => {
// 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 環(huán)境api代碼的能力
enableRemoteModule: true, // 是否允許使用remote
contextIsolation: false,
// 加載本地圖片
webSecurity: false, // 允許跨域
webviewTag: true // 允許webview
},
icon: path.join(__static, './favicon.ico'),
show: false,
autoHideMenuBar: true, // 隱藏頂部工具欄,生產(chǎn)環(huán)境時設(shè)置為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天前的日志文件,節(jié)約硬盤空間
deleteOldLogFiles()
// 監(jiān)聽控制臺錯誤輸出的事件
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);
}
});
// 生產(chǎn)環(huán)境下隱藏此函數(shù)
// 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 () { // 收到渲染進(jìn)程的窗口最小化操作的通知,并調(diào)用窗口最小化函數(shù),執(zhí)行該操作
mainWindow.minimize()
})
// 2. 窗口 最大化、恢復(fù)
ipcMain.on('window-max', function () {
if (mainWindow.isMaximized()) { // 為true表示窗口已最大化
mainWindow.restore() // 將窗口恢復(fù)為之前的狀態(tài).
} else {
mainWindow.maximize()
}
})
// 3. 關(guān)閉窗口
ipcMain.on('window-close', function () {
mainWindow.close()
})
// 刷新窗口
ipcMain.on('window-reload', function () { // 收到渲染進(jìn)程的窗口最小化操作的通知,并調(diào)用窗口最小化函數(shù),執(zhí)行該操作
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() // 關(guān)閉應(yīng)用
})
})
}
app.whenReady().then(async () => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// 除了 macOS 外,當(dāng)所有窗口都被關(guān)閉的時候退出程序。 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系統(tǒng)
if (process.platform == 'darwin') {
return 1
}
// 這是windows系統(tǒng)
if (process.platform == 'win32') {
return 2
}
// 這是linux系統(tǒng)
if (process.platform == 'linux') {
return 3
}
}
關(guān)鍵配置就在102行附近,createWindow函數(shù)的new BrowserWindow里,nodeIntegration: true和enableRemoteModule: true。這2個配置,一個是允許頁面支持node環(huán)境及其api調(diào)用。一個允許頁面使用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系統(tǒng)
if (process.platform == "darwin") {
return 1;
}
//這是windows系統(tǒng)
if (process.platform == "win32") {
return 2;
}
//這是linux系統(tǒng)
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函數(shù),就是獲取config文件的函數(shù)。所以外部只要調(diào)用這個readConfig函數(shù),就可以獲取外部配置文件的信息了(你可以在main.js里調(diào)用,就是在項目加載時,就讀取config.json這個配置文件)。
例如:
import { readConfig } from '@/utils/getBaseUrl.js'
// let applicationType = 'website' // 如果最后打包的是網(wǎng)站,就打開這個
let applicationType = "exe" // 如果最后打包的是exe應(yīng)用,就打開這個
if (applicationType === 'exe') {
(async function () {
const res = await readConfig()
axios.defaults.baseURL = res.baseUrl
Vue.prototype.$baseURL = res.baseUrl
window.$config = res
})()
}
// 因為我原來的項目是可以打包成網(wǎng)站與桌面應(yīng)用,但是在網(wǎng)頁版中,window.require('electron')返回的是undefined,所以這里才會用applicationType來區(qū)分,如果打包后的是exe應(yīng)用時,才去讀取安裝目錄下的config.json文件
最后
這篇文章就講這個外部配置文件的生成與獲取,如果大家有興趣的話,會找個時間分享一下,electron的桌面的版本更新下載的功能,就像其他桌面應(yīng)用一樣,點擊更新按鈕,自動下載與更新應(yīng)用的功能。
附上我當(dāng)前項目的vue與electron版本文章來源:http://www.zghlxwxcb.cn/news/detail-445522.html
"vue": "^2.6.11",
"electron": "^13.0.0",
"electron-packager": "^15.4.0",
這就是這篇文章的主要內(nèi)容了,如果這篇文章對你有幫助,記得留下你的點贊了,謝謝啦~~文章來源地址http://www.zghlxwxcb.cn/news/detail-445522.html
到了這里,關(guān)于electron框架的自定義外部配置文件的配置與讀取的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!