Electron应用创建和打包

news/2024/10/3 23:01:07/

一、创建项目目录

创建NodeJs项目目录,项目有关的文件、依赖包都将在本目录创建和安装。

mkdir hello_electron & cd hello_electron

CMD执行以上命令将在用户目录下创建hello_electron并进入该目录。当然也可以手动在任何地方创建目录,cmd中cd 路径进入目录。

二、项目初始化

npm init

初始化时按提示输入必要配置内容,程序名、版本、简介、入口、作者,其他的内容不输入直接回车。

C:\Users\Admin\NodejsProjects\hello>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.See `npm help init` for definitive documentation on these fields
and exactly what they do.Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.Press ^C at any time to quit.
package name: (hello)
version: (1.0.0)
description: myapp
entry point: (index.js)
test command:
git repository:
keywords:
author: me
license: (ISC)
About to write to C:\Users\Admin\NodejsProjects\hello\package.json:{"name": "hello","version": "1.0.0","description": "electron_app","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "me","license": "ISC"
}Is this OK? (yes)

如果初始化没有提示输入生成package.json,那么请手动创建

{"name": "hello","version": "1.0.0","description": "electron_app","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "","license": "ISC"
}

三、安装Electron

1.执行安装

electron作为nodejs项目的依赖包安装,执行命令安装:

npm install electron --save
# 网络有问题请使用cnpm代替,,前提是使用npm安装了cnpm模块,cnpm安装不再详述
cnpm add electron --save
# cnpm安装的包体积稍大,网络存在问题推荐使用yarn添加包,前提是使用npm安装了yarn模块
yarn add electron --save

等待安装

C:\Users\Admin\NodejsProjects\hello>cnpm install electron --save
√ Installed 1 packages
√ Linked 82 latest versions
[1/2] scripts.postinstall electron@15.1.0 › @electron/get@1.13.0global-agent@2.2.0 › core-js@^3.6.5 run "node -e \"try{require('./postinstall')}catch(e){}\"", root: "C:\\Users\\Admin\\NodejsProjects\\hello\\node_modules\\_core-js@3.18.1@core-js"
Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!The project needs your help! Please consider supporting of core-js:
> https://opencollective.com/core-js
> https://patreon.com/zloirock
> https://paypal.me/zloirock
> bitcoin: bc1qlea7544qtsmj2rayg0lthvza9fau63ux0fstczAlso, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)[1/2] scripts.postinstall electron@15.1.0 › @electron/get@1.13.0global-agent@2.2.0 › core-js@^3.6.5 finished in 232ms
[2/2] scripts.postinstall electron@latest run "node install.js", root: "C:\\Users\\Admin\\NodejsProjects\\hello\\node_modules\\_electron@15.1.0@electron"
[2/2] scripts.postinstall electron@latest finished in 5s
√ Run 2 scripts
Recently updated (since 2021-09-25): 3 packages (detail see file C:\Users\Admin\NodejsProjects\hello\node_modules\.recently_updates.txt)Today:electron@latest(15.1.0) (00:39:02)
√ All packages installed (87 packages installed from npm registry, used 35s(network 30s), speed 9.19KB/s, json 82(277.92KB), tarball 0B)C:\Users\Admin\NodejsProjects\hello>

安装完成后,package.json自动添加electorn配置信息

"devDependencies": {"electron": "^19.0.3"}

使用–save参数安装,则在package.json添加dependencies

使用–save-dev参数安装,则在package.json添加devDependencies

区别在于dependencies是实际环境中使用,devDependencies在开发环境下使用。

2.配置启动方式

安装好electron之后,想要启动electron应用,还需要在package.json文件中添加启动方式

"scripts": {"start": "electron ."}

scripts项添加start为electron .

四、创建应用

创建应用前需要了解的是electron应用工作基本原理,首先electron是由chromium浏览器内核+nodejs,前端技术通过nodejs调用系统层功能,来达到桌面应用开发的目的,因此创建应用基本是js和html文件为主,这里需要创建index.js入口文件和html显示界面。

1.index.js

应用入口文件,文件名对应package.json->main

javascript">// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')function createWindow () {// Create the browser window.const mainWindow = new BrowserWindow({width: 800,height: 600,webPreferences: {preload: path.join(__dirname, 'preload.js')}})// and load the index.html of the app.mainWindow.loadFile('index.html')// Open the DevTools.// mainWindow.webContents.openDevTools()
}// 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.whenReady().then(() => {createWindow()app.on('activate', function () {// 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 (BrowserWindow.getAllWindows().length === 0) createWindow()})
})// Quit when all windows are closed, except on macOS. 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', function () {if (process.platform !== 'darwin') app.quit()
})// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

入口文件运行于主进程,作为nodejs应用运行,可直接使用nodejs功能。

2.index.html

显示页面,文件名对应index.js加载html文件名

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"><title>Hello World!</title></head><body><h1>Hello World!</h1>We are using Node.js <span id="node-version"></span>,Chromium <span id="chrome-version"></span>,and Electron <span id="electron-version"></span>.<!-- You can also require other files to run in this process --><script src="./renderer.js"></script></body>
</html>

显示界面,运行于渲染进程,html可以加载js文件,与项目入口index.js文件不同的是,页面加载的js运行于渲染进程。渲染进程不能直接通过nodejs调用系统功能,但是可以通过ipc与主进程进行通信,达到调用系统层目的,具体这里不再详述。

3.启动项目

npm start

执行后正常就可以看到electron窗口和界面了。

五、安装指定版本包

由于electron版本差异较大,如果需要使用指定版本,可以在安装electron前先创建package.json,如果有package-lock.json文件先删除,设置"dependencies"和"devDependencies":

"dependencies": {"electron": "^15.1.0"},"devDependencies": {"electron": "^15.1.0","electron-packager": "^15.4.0"}

执行安装命令:

npm install

"dependencies"和"devDependencies"中标明的包将会通过npm进行安装。

有于electron新版本在安全方面做了更多的优化,因此官方建在没有特殊需求情况下请使用最新版本。

electronpackager_276">六、electron-packager项目打包

项目打包将开发好的项目打包为可发布的程序,执行目录exe主程序自动加载相关文件并显示界面,不需要通过命令行。且可以通过打包为不同系统对应的程序发布。

electronpackage_282">1.安装electron-package

npm install electron-packager --save-dev

安装完成后,package.json将自动在devDependencies添加electron-packager,表示electron-packager在开发环境运行

"devDependencies": {"electron-packager": "^15.4.0"}

2.打包参数

在package.json中指定打包参数,指定打包目录、程序名称、运行平台、位数等

"scripts": {"start": "electron .","build": "electron-packager .  hello_electron --platform=win32 --arch=x64 --ignore=node_modules/electron-*"}

build参数如下:

electron-packager 项目目录 app名称 --platform=平台 --arch=架构 --ignore=要忽略的目录或文件
  • arch:ia32(32位) 、x64(64位)、armv7l(ARM)、all

  • plateform:linux (Linux平台), win32 (Windows平台), darwin (MacOSX), mas , all

OS X (also known as darwin)
Mac App Store (also known as mas)

3.执行打包

npm run build

执行命令进行打包

执行成功:

C:\Users\Admin\NodejsProjects\hello>npm run build> hello@1.0.0 build C:\Users\Admin\NodejsProjects\hello
> electron-packager .  hello_electron --platform=win32 --arch=x64 --ignore=node_modules/electron-*Packaging app for platform win32 x64 using electron v15.1.0
WARNING: Found 'electron' but not as a devDependency, pruning anyway
Wrote new app to C:\Users\Admin\NodejsProjects\hello\hello_electron-win32-x64C:\Users\Admin\NodejsProjects\hello>

其中WARNING警告electron没有作为开发环境使用,虽然打包成功,但为了避免出现未知错误,建议在package.json中devDependencies添加electron,之后再重新执行打包:

"devDependencies": {"electron": "^15.1.0"}

4.相关问题

(1)打包为macos操作系统的软件包时失败,提示如下信息:

Cannot create symlinks (on Windows hosts, it requires admin privileges); skipping darwin platform

原因是命令行没有权限执行,解决方法是通过管理员权限启动cmd命令行重新执行打包。

electronbuild_375">七、electron-build项目打包

electron-build相比electron-package功能更丰富些,electron-build打包的项目可以同时打包.zip绿色版和.exe安装版,同时还会能配置是否asar打包,打包结果中海油一个未做任何压缩的版本用于查看打包结果是否正确,electron-build通过配置可以在打包时移动文件目录位置,配置跨平台配置打包等等,当然跨平台配置不是electron-build能够交叉打包,而是在对应的平台进行构建打包。

1.package.json配置

electron-build在package.json文件中主要配置build项

{"name": "pinmashi","version": "1.0.0","description": "","main": "index.min.js","scripts": {"start": "electron .","build": "node-gyp configure build","rebuild": "node-gyp rebuild","clean": "node-gyp clean","electron-build": "electron-builder"},"build": {"productName": "PinMaShi",		//项目名"appId": "com-pinmashi-app",	//appid一般是com-项目名-app"directories": {"output": "dist"		//输出目录},"asar": true,	//是否asar打包(asar打包吧app目录作为一个asar文件)"files": [		//配置打包的文件目录,!开头表示忽略"dist/electron/**/*","**/*","!.vscode","!block_modules","!src","!other",		//忽略目录"!*.gyp",		//忽略gyp后缀的所有文件"!*.zip","!*.rar","!*.7z","!*.txt","!README.md",	//忽略README.md文件"!release","!*.dev.js","!renderer.js","!index.js"],"extraResources": [{"from": "./block_modules/",		//移动block_modules目录"to": "block_modules"			//到app同级目录}],"nsis": {	//windows安装包"oneClick": false,"allowElevation": true,"allowToChangeInstallationDirectory": true,"installerIcon": "build/icons/icon.ico","uninstallerIcon": "build/icons/icon.ico","installerHeaderIcon": "build/icons/icon.ico","createDesktopShortcut": true,	//创建桌面图标"createStartMenuShortcut": true,	//创建开始菜单"shortcutName": "PinMaShi","include": "build/script/installer.nsh"	//安装需要的脚本},"dmg": {	//macos安装包"contents": [{"x": 410,"y": 150,"type": "link","path": "/Applications"},{"x": 130,"y": 150,"type": "file"}]},"mac": {	//macos配置"icon": "build/icons/icon.icns"},"win": {	//windows配置"icon": "build/icons/icon.ico","target": [{"target": "nsis","arch": ["x64"]},{"target": "zip","arch": ["x64"]}]},"linux": {	//linux配置"icon": "build/icons"}},"author": "","license": "GPL3","dependencies": {"cheerio": "^1.0.0-rc.12","compressing": "^1.6.2","ssh2": "^1.11.0"},"devDependencies": {"electron": "^20.0.2","electron-builder": "^23.6.0","node-addon-api": "^5.0.0","node-gyp": "^9.3.0"}
}
2.图标

在项目目录下创建以下文件:

#图片
build/icons/256x256.png
#图标
build/icons/icon.ico
3.安装脚本

在项目目录下创建build\script\installer.nsh

; Script generated by the HM NIS Edit Script Wizard.; HM NIS Edit Wizard helper defines custom install default dir
!macro preInitSetRegView 64WriteRegExpandStr HKLM "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Program Files"WriteRegExpandStr HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Program Files"SetRegView 32WriteRegExpandStr HKLM "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Program Files"WriteRegExpandStr HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Program Files"
!macroend
4.执行打包
electron-builder

http://www.ppmy.cn/news/1534139.html

相关文章

【YashanDB知识库】如何dump数据文件,转换rowid, 查询对应内容

本文来自YashanDB官网&#xff0c;具体内容可见https://www.yashandb.com/newsinfo/7459464.html?templateId1718516 问题现象 客户环境有时候会遇到文件损坏的情况&#xff0c;需要dump文件&#xff0c;根据rowid查询数据情况。 问题的风险及影响 熟练掌握崖山数据文件du…

虚拟机、ubantu不能连接网络,解决办法

虚拟机、ubantu不能连接网络&#xff0c;解决办法 物理机OS&#xff1a; [Windows10 专业版](https://so.csdn.net/so/search?qWindows10 专业版&spm1001.2101.3001.7020) 虚拟机平台&#xff1a; VMware Workstation 16 Pro 虚拟机OS&#xff1a; Ubuntu 18.04 自动配…

定制化CRM如何重塑科技服务领域的生态链?

企业不仅面临着技术创新与知识产权保护的双重挑战&#xff0c;还需在激烈的市场竞争中构建稳固的客户关系与广泛的合作网络。传统的CRM&#xff08;客户关系管理&#xff09;系统&#xff0c;往往局限于企业内部的数据管理与流程优化&#xff0c;难以满足当前复杂多变的业务需求…

JVM相关的命令汇总

一、简介 虽然目前市场上有很多成熟的 JVM 可视化监控分析工具&#xff0c;但是所有的工具其实都依赖于 JDK 的接口和底层相关的命令&#xff0c;了解这些命令的使用对于在紧急情况下排查 JVM 相关的线上故障&#xff0c;会有更加直观的帮助。 下面一起来看看 JVM 常用的命令…

各种 JIT(Just-In-Time) 编译器

JIT&#xff08;Just-In-Time&#xff09;编译器广泛应用于各种编程语言和运行时环境中&#xff0c;不同的语言和平台都实现了各自的 JIT 编译器来提升执行效率。以下是一些常见的使用 JIT 技术的编译器和虚拟机&#xff1a; 1. Java HotSpot 语言&#xff1a;Java描述&#…

小红书制作视频如何去原视频音乐,视频如何去原声保留背景音乐?

在视频编辑、音乐制作或个人娱乐中&#xff0c;有时我们希望去掉视频中的原声&#xff08;如对话、解说等&#xff09;&#xff0c;仅保留背景音乐。这种处理能让观众更加聚焦于视频的氛围或节奏&#xff0c;同时也为创作者提供了更多创意空间。选择恰当的背景音乐&#xff0c;…

简单分享下Python和MySQL管理和执行测试用例

在软件开发过程中&#xff0c;自动化测试是非常重要的一环。本文将介绍如何使用Python和MySQL来管理和执行测试用例&#xff0c;并处理用例之间的依赖关系和参数化问题。我们将通过几个简单的步骤来构建一个完整的测试框架。 项目需求概述 我们的目标是创建一个测试框架&#…

android Activity生命周期

android 中一个 activity 在其生命周期中会经历多种状态。 您可以使用一系列回调来处理状态之间的转换。下面我们来介绍这些回调。 onCreate&#xff08;创建阶段&#xff09; 初始化组件&#xff1a;在这个阶段&#xff0c;Activity的主要工作是进行初始化操作。这包括为Ac…