Electron开发文档
环境安装 安装node npm 创建项目 1从github拉取示例项目代码 git clone github.com/electron/el…
2进入项目目录electron-quick-start
3修改配置main.js文件 将mainWindow.loadFile('index.html')改为mainWindow.loadFile('./dist/index.html')
4将编译后的vue dist文件夹考入electron-quick-start
5设置electron镜像 npm config set ELECTRON_MIRROR=npm.taobao.org/mirrors/ele…
6在electron-quick-start目录下运行npm install安装依赖包,运行npm start命令运行项目
打包 1导入 Electron Forge 到应用文件夹: npx @electron-forge/cli import
2打包应用 npm run mark
开发 1启动vue项目,在electron项目的main.js中使用loadURL方法load vue项目的地址
2使用node API 在electron项目的main.js中配置node可用 nodeIntegration: true,
引入node包时使用window.require方法代替require方法否则进入失败
在vue文件中调用node api
3开启调试 BrowserWindow.webContents.openDevTools();//开启调试
技术预研
1在vue中使用node api
引入node包时使用window.require方法代替require方法否则进入失败
示例:在vue中调用node api 在命令终端中执行删除文件夹命令
const child_process = window.require('child_process');
const util = window.require('util');
const exec = til.promisify(child_process.exec);
const appPath = 'C:/Users/zhaoxin/Desktop';
const runClean = async function () {
//执行cmd 命令
await exec(rmdir test , { cwd: appPath });
};
runClean();
2在主进程中监听文件变化,并发送消息到渲染进程 Electron进程间通信有多种,此处只介绍一种 主进程中代码: const chokidar = require('chokidar'); //发送文件改变消息 function sendFileDataToRender (mainWindow, data) { console.log(data) mainWindow.webContents.send('file-changed', data); } //监听文件变化 function initFileListener (mainWindow) { const watcher = chokidar.watch('C:\Users\zhaoxin\Desktop\electron', { ignored: /[/\]./, persistent: true }); const log = console.log.bind(console); watcher .on('add', function (path) { // log('File', path, 'has been added'); sendFileDataToRender(mainWindow, { type: 'FileAdd', path: path }); }) .on('addDir', function (path) { // log('Directory', path, 'has been added'); sendFileDataToRender(mainWindow, { type: 'DirAdd', path: path }); }) .on('change', function (path) { // log('File', path, 'has been changed'); sendFileDataToRender(mainWindow, { type: 'FileChanged', path: path }); }) .on('unlink', function (path) { // log('File', path, 'has been removed'); sendFileDataToRender(mainWindow, { type: 'FileRemoved', path: path }); }) .on('unlinkDir', function (path) { // log('Directory', path, 'has been removed'); sendFileDataToRender(mainWindow, { type: 'DirRemoved', path: path }); }) .on('error', function (error) { log('Error happened', error); sendFileDataToRender(mainWindow, { type: 'Error', path: 'error' }); }) .on('ready', function () { // log('Initial scan complete. Ready for changes.'); sendFileDataToRender(mainWindow, { type: 'ScanReady', }); }) .on('raw', function (event, path, details) { //log('Raw event info:', event, path, details); sendFileDataToRender(mainWindow, { type: 'Raw', path: path }); }); }
Vue项目中代码: //监听electron 主进程消息 const ipcRenderer = window.require('electron').ipcRenderer ipcRenderer.on('file-changed', function (event, arg) { // 接收到Main进程返回的消息 console.log(arg); })
渲染进程发送消息到主进程使用ipcRenderer.send方法,主进程中使用ipcRenderer.on进行监听