项目中使用了:本地配置,sqlite,log,这些都是需要我们自定义路径的,但是在获取路径时发生问题,以下是我的获取方法:
//background.js
nodeIntegration: true
//js
const { app} = require('electron')
由于首次使用electron,对electron不熟悉,在调用引用app时一直报getPath为undefined ,
其实app在这里也根本没获取到
后面就想到主进程能使用app,那我在主进程中先获取,然后发送给渲染进程不就得了,以下是我的两种办法:
1.主进程发送给渲染进程
background.js
async function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
width: 1800,
height: 1000,
//有边框
frame: true,
//独占全屏
//fullscreen: true,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
}
});
//是否可以调解大小
//win.setResizable(false);
//全屏,下方有任务栏
//win.maximize()
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
//开启调试
if (!process.env.IS_TEST){
win.webContents.openDevTools()
}
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html')
}
//获取配置文件,并发送给渲染进程
win.webContents.send('config-path', path.dirname(app.getAppPath()))
}
最后一行是重点,这里的getAppPath(),也是app获取路径的一种方法,详情看https://www.electronjs.org/zh/docs/latest/api/app#appgetapppath
js
const { ipcRenderer } = require('electron')
let BASE_DIR=null ;
ipcRenderer.on('config-path',(a,b)=>{
BASE_DIR=b;
})
这里有一个问题,只推送一次,如果刷新情况下,BASE_DIR会还原,这里的BASE_DIR就会出现null的情况.
2.主进程,渲染进程双向通信
background.js
async function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
width: 1800,
height: 1000,
//有边框
frame: true,
//独占全屏
//fullscreen: true,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
}
});
//是否可以调解大小
//win.setResizable(false);
//全屏,下方有任务栏
//win.maximize()
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
//开启调试
if (!process.env.IS_TEST){
win.webContents.openDevTools()
}
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html')
}
//获取配置文件,并发送给渲染进程
//win.webContents.send('config-path', path.dirname(app.getAppPath()))
}
ipcMain.handle('get-path', () => {
return path.dirname(app.getAppPath())
});
js
const { ipcRenderer } = require('electron')
let BASE_DIR=null ;
ipcRenderer.invoke('get-path').then((resul) => {
BASE_DIR= resul;
})
这种方式,就不存在刷新后BASE_DIR变null的情况