Electron项目的创建及编译启动

本文详细介绍了如何使用vue-cli3创建并配置一个Electron应用,包括使用cnpm加速下载,不使用SimulatedGREG/electron-vue的原因,安装/升级vue-cli3,创建vue项目,手动和自动安装electron,以及项目配置、编译和启动。同时,还提到了项目开发中的一些经验,如设置窗口大小、取消跨域限制和菜单栏,以及设置图标和标题等。
摘要由CSDN通过智能技术生成

目录
1 创建项目

1.1 使用cnpm加速下载

1.2 为什么不使用SimulatedGREG/electron-vue

1.3 安装/升级vue-cli3

1.4 创建vue项目

1.5 自动安装electron

1.6 手动安装electron

1.7 编译并启动APP

2 配置项目

2.1 配置ESLint代码格式检查工具

2.2 配置vue

3 项目基本设定

3.1 主进程和渲染进程简介

3.2 APP窗口大小

3.3 取消跨域限制

3.4 取消菜单栏

3.5 设置APP窗口图标

3.6 设置APP窗口标题栏名称

4 build最终产品

4.1 设置APP及安装包图标

4.2 设置APP名称

4.3 打包APP

4.4 可能出现的错误

5 关于项目开发的一些经验

5.1 src目录结构参考

5.2 换肤功能的实现

5.3 从Electron4.x升级到5.x

5.4 注册快捷键打开devTools

1 创建项目
1.1 使用cnpm加速下载
npm有时下载速度很慢,可以安装cnpm,从国内淘宝镜像下载,执行以下命令:

npm install -g cnpm --registry=https://registry.npm.taobao.org
以后npm直接替换成cnpm使用。

1.2 为什么不使用SimulatedGREG/electron-vue
SimulatedGREG/electron-vue已经很久没有更新了,而且其生成的工程结构并不是vue-cli3。所以放弃使用。

1.3 安装/升级vue-cli3
先执行以下命令,确认下本地安装的vue-cli版本:

vue -V
在写本文时,我使用的是3.8.4版本。

如果本地使用的是vue-cli2.x或者更早版本,可先卸载:

cnpm uninstall vue-cli -g
※注:vue-cli3使用了新的npm包名,与旧版本不一样。
如果还没有安装vue-cli3,先执行以下命令安装:

cnpm install @vue/cli -g
如果你已安装vue-cli3,但不是最新版本,可执行以下命令升级:

(我这里使用cnpm并没有完成升级,所以使用了npm)

npm update @vue/cli -g
1.4 创建vue项目
找个喜欢的目录,执行以下命令,创建vue项目:

(这里把项目名称定为electron-vue-demo)

vue create electron-vue-demo
会出现以下选项(如果熟悉此步骤可跳过本节内容):

Vue CLI v3.8.4
? Please pick a preset: (Use arrow keys)
default (babel, eslint)

Manually select features
选择“Manually select features” (自定义安装)。

? Check the features needed for your project: (Press to select, to t
oggle all, to invert selection)
❯◉ Babel
◯ TypeScript
◯ Progressive Web App (PWA) Support
◉ Router
◉ Vuex
◉ CSS Pre-processors
◉ Linter / Formatter
◯ Unit Testing
◯ E2E Testing
这里选择了常用的模块,请根据实际需求进行选择。

? Use history mode for router? (Requires proper server setup for index fallback
in production) (Y/n) n
如果选择了router,这里会询问是否使用history模式。

vue-router 默认使用hash模式(即通过url#hash来跳转页面),使用URL的hash来模拟一个完整的 URL,当URL改变时,页面不会重新加载。 如果使用history,URL就像正常的url,例如 http://yoursite.com/user/id ,比较好看。但是还需要后台配置支持。

这里我们选择“n”。

? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported
by default): (Use arrow keys)
Sass/SCSS (with dart-sass)
Sass/SCSS (with node-sass)
Less
❯ Stylus
选择CSS预处理模块,这里我们使用“Stylus”。

? Pick a linter / formatter config: (Use arrow keys)
ESLint with error prevention only
ESLint + Airbnb config
❯ ESLint + Standard config
ESLint + Prettier
选择ESLint代码格式检查工具的配置,选择“ESLint + Standard config”,标准配置。

? Pick additional lint features: (Press to select, to toggle all, <i

to invert selection)
❯◉ Lint on save
◯ Lint and fix on commit
Line on save表示在保存代码的时候,进行格式检查。

Lint and fix on commit表示在git commit的时候自动纠正格式。

这里只选择“Lint on save”。

? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.?
In dedicated config files
❯ In package.json
这里问把 babel, postcss, eslint 这些配置文件放哪?

In dedicated config files 表示独立文件

In package.json 表示放在package.json里

这里选择“In package.json”。

? Save this as a preset for future projects? (y/N) N
是否为以后的项目保留这些设置?选择“N”。

然后耐心等待项目安装完成。

1.5 自动安装electron
※注:此过程可能需要科学上网,由于直接从国外镜像下载较慢,可能需要等待很漫长的时间。如果你对自己的网速没有超强自信,请跳过本节,前往1.6小节手动安装。
进入到项目根目录,执行:

vue add electron-builder
在安装过程中,很可能会卡在这一步不动了:

node ./download-chromedriver.js
没关系,我们先强制结束掉。再执行一次vue add electron-builder,然后就可以顺利通过了。

接下来出现配置选项:

? Choose Electron Version (Use arrow keys)
^3.0.0
^4.0.0
❯ ^5.0.0
选择Electron版本。选择 “^5.0.0”。

然后耐心等待安装完成。如果中间出现错误中断了,请重复此步骤。

安装完成后会自动在src目录下生成background.js并修改了package.json。

※注:由于网络原因,如果中间出现过中断失败,再次重新安装可能会很快完成,但实际上electron可能并未安装完全。建议完成以上步骤后,直接删除项目根目录的node_modules/,并且执行cnpm install,从国内镜像重新安装所有依赖包。
1.6 手动安装electron
※注:如果已经通过1.5章节的操作,请直接跳过本小节。
修改package.json,添加以下7行:

“scripts”: {
“serve”: “vue-cli-service serve”,
“build”: “vue-cli-service build”,
“lint”: “vue-cli-service lint”,

  • “electron:build”: “vue-cli-service electron:build”,
  • “electron:serve”: “vue-cli-service electron:serve”,
  • “postinstall”: “electron-builder install-app-deps”,
  • “postuninstall”: “electron-builder install-app-deps”
    },
  • “main”: “background.js”,
    “dependencies”: {
    “core-js”: “^2.6.5”,
    “vue”: “^2.6.6”,
    “vue-router”: “^3.0.1”,
    “vuex”: “^3.0.1”
    },
    “devDependencies”: {
    “@vue/cli-plugin-babel”: “^3.8.0”,
    “@vue/cli-plugin-eslint”: “^3.8.0”,
    “@vue/cli-service”: “^3.8.0”,
    “@vue/eslint-config-standard”: “^4.0.0”,
    “babel-eslint”: “^10.0.1”,
  • “electron”: “^5.0.6”,
    “eslint”: “^5.16.0”,
    “eslint-plugin-vue”: “^5.0.0”,
    “stylus”: “^0.54.5”,
    “stylus-loader”: “^3.0.2”,
  • “vue-cli-plugin-electron-builder”: “^1.3.5”,
    “vue-template-compiler”: “^2.6.10”
    },

    新建src/background.js
    在src目录下新建background.js,复制以下代码:

‘use strict’

import { app, protocol, BrowserWindow } from ‘electron’
import {
createProtocol,
installVueDevtools
} from ‘vue-cli-plugin-electron-builder/lib’

const isDevelopment = process.env.NODE_ENV !== ‘production’

// Keep a global reference of the window object, if you don’t, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{
scheme: ‘app’,
privileges: {
secure: true,
standard: true
}
}])

function createWindow () {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})

if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
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.on(‘closed’, () => {
win = null
})
}

// Quit when all windows are closed.
app.on(‘window-all-closed’, () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== ‘darwin’) {
app.quit()
}
})

app.on(‘activate’, () => {
// On macOS it’s common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on(‘ready’, async () => {
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
try {
await installVueDevtools()
} catch (e) {
console.error(‘Vue Devtools failed to install:’, e.toString())
}
}
createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (process.platform === ‘win32’) {
process.on(‘message’, data => {
if (data === ‘graceful-exit’) {
app.quit()
}
})
} else {
process.on(‘SIGTERM’, () => {
app.quit()
})
}
}
以上代码是1.5小节使用自动化方式安装后生成的。

安装依赖包
在项目根目录执行,安装全部依赖包:

cnpm install
如果安装过程中报错:Error: post install error, please remove node_modules before retry!可以忽略,不影响后续使用。

1.7 编译并启动APP
执行以下命令,开始编译APP,并启动开发环境APP:

npm run electron:serve
首次启动可能会等待很久,出现以下信息:

INFO Launching Electron…
Failed to fetch extension, trying 4 more times
Failed to fetch extension, trying 3 more times
Failed to fetch extension, trying 2 more times

这是因为在请求安装vuejs devtools插件。需要科学上网才能安装成功。如果不能科学上网也没关系,耐心等待5次请求失败后会自动跳过。

编译成功后,就会出现开发环境的APP了。

1. 安装Vue CLI 首先,需要确保已经安装了Node.js和npm。然后在终端中输入以下命令来安装Vue CLI: ``` npm install -g @vue/cli ``` 2. 创建Vue项目 在终端中输入以下命令来创建一个新的Vue项目: ``` vue create my-electron-app ``` 在创建过程中,可以选择使用默认配置或手动选择插件和配置。 3. 安装electron-builder 在终端中输入以下命令来安装electron-builder: ``` npm install electron-builder --save-dev ``` 4. 配置package.json 在package.json文件中添加以下内容: ``` "build": { "productName": "MyElectronApp", "appId": "com.example.my-electron-app", "directories": { "output": "build" }, "files": [ "dist/**/*", "node_modules/**/*", "package.json" ], "win": { "icon": "public/icon.ico", "target": "nsis" }, "nsis": { "oneClick": false, "allowElevation": true, "installerIcon": "public/icon.ico", "uninstallerIcon": "public/icon.ico", "installerHeaderIcon": "public/icon.ico", "createDesktopShortcut": true, "createStartMenuShortcut": true, "shortcutName": "MyElectronApp" } } ``` 其中,productName、appId、icon等可以根据实际情况进行修改。 5. 修改main.js 在src/main.js文件中添加以下内容: ``` const { app, BrowserWindow } = require('electron') let win function createWindow() { win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) win.loadFile('dist/index.html') win.on('closed', () => { win = null }) } app.on('ready', createWindow) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (win === null) { createWindow() } }) ``` 6. 编译打包 在终端中输入以下命令来编译打包应用: ``` npm run build ``` 打包后的应用程序将保存在build目录中。 7. 运行应用 在终端中输入以下命令来启动应用: ``` npm start ``` 应用程序将在Electron中运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值