前言

之前考虑了很久准备使用electron练练手,写一个桌面应用。一开始打算使用electron-vue直接创建,无奈该项目所使用的版本依赖太过古老,只能自己创建了。


构建过程

使用vue-cli初始化项目

# vue-cli初始化
vue create -d my-project

安装electron

# electron install
npm install electron -D or yarn add electron -D

# 但是这里建议使用 cnpm install electron -D
# 原因是前两者貌似安装下来都会在构建时候出现问题

配置eslint

启动electron

首先在项目根目录下创建electron启动文件

不建议使用electron.js命名

// elec.js
const { app, BrowserWindow } = require('electron')

function createWindow() {
  // 创建浏览器窗口
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  // 这里注意入口文件是vue打包后的dist下index.html
  // 加载 index.html
  win.loadFile('dist/index.html')

  // 打开开发者工具
  win.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// 部分 API 在 ready 事件触发后才能使用。
app.whenReady().then(createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // 在 macOS 上,除非用户用 Cmd + Q 确定地退出,
  // 否则绝大部分应用及其菜单栏会保持激活。
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // 在macOS上,当单击dock图标并且没有其他窗口打开时,
  // 通常在应用程序中重新创建一个窗口。
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

简单配置下vue.config.js

'use strict'
const path = require('path')

function resolve(dir) {
  return path.join(__dirname, dir)
}
// 注意这里publicPath: './'
module.exports = {
  publicPath: './',
  outputDir: 'dist',
  assetsDir: 'static',
  configureWebpack: {
    resolve: {
      alias: {
        '@': resolve('src')
      }
    }
  }
}

修改package.json

...
"script": {
  "electron_dev": "npm run build && electron elec.js"
}
...

预览

不出问题在终端运行 npm run electron_dev 即可弹出GUI

Last modification:March 27th, 2020 at 09:06 pm
如果觉得我的文章对你有用,请随意赞赏