Electron应用创建和打包

一、创建项目目录

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

cmd 复制代码
mkdir hello_electron & cd hello_electron

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

二、项目初始化

cmd 复制代码
npm init

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

shell 复制代码
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,那么请手动创建

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项目的依赖包安装,执行命令安装:

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

等待安装

python 复制代码
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.0 › global-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: bc1qlea7544qtsmj2rayg0lthvza9fau63ux0fstcz

Also, 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.0 › global-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配置信息

json 复制代码
"devDependencies": {
    "electron": "^19.0.3"
  }

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

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

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

2.配置启动方式

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

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文件名

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.启动项目

python 复制代码
npm start

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

五、安装指定版本包

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

python 复制代码
"dependencies": {
    "electron": "^15.1.0"
  },
  "devDependencies": {
    "electron": "^15.1.0",
    "electron-packager": "^15.4.0"
  }

执行安装命令:

python 复制代码
npm install

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

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

六、electron-packager项目打包

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

1.安装electron-package

python 复制代码
npm install electron-packager --save-dev

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

python 复制代码
"devDependencies": {
    "electron-packager": "^15.4.0"
  }

2.打包参数

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

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

build参数如下:

undefined 复制代码
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.执行打包

python 复制代码
npm run build

执行命令进行打包

执行成功:

python 复制代码
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-x64

C:\Users\Admin\NodejsProjects\hello>

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

python 复制代码
"devDependencies": {
    "electron": "^15.1.0"
  }

4.相关问题

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

bash 复制代码
Cannot create symlinks (on Windows hosts, it requires admin privileges); skipping darwin platform

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

七、electron-build项目打包

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

1.package.json配置

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

json 复制代码
{
  "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.图标

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

bash 复制代码
#图片
build/icons/256x256.png
#图标
build/icons/icon.ico
3.安装脚本

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

bash 复制代码
; Script generated by the HM NIS Edit Script Wizard.

; HM NIS Edit Wizard helper defines custom install default dir
!macro preInit
    SetRegView 64
    WriteRegExpandStr HKLM "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Program Files"
    WriteRegExpandStr HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Program Files"
    SetRegView 32
    WriteRegExpandStr HKLM "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Program Files"
    WriteRegExpandStr HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Program Files"
!macroend
4.执行打包
bash 复制代码
electron-builder
相关推荐
Watermelo6178 分钟前
详解js柯里化原理及用法,探究柯里化在Redux Selector 的场景模拟、构建复杂的数据流管道、优化深度嵌套函数中的精妙应用
开发语言·前端·javascript·算法·数据挖掘·数据分析·ecmascript
wuningw2 小时前
ant-design-ui的Select选择器多选时同时获取label与vaule值
ui·arcgis
一个处女座的程序猿O(∩_∩)O2 小时前
小型 Vue 项目,该不该用 Pinia 、Vuex呢?
前端·javascript·vue.js
燃先生._.8 小时前
Day-03 Vue(生命周期、生命周期钩子八个函数、工程化开发和脚手架、组件化开发、根组件、局部注册和全局注册的步骤)
前端·javascript·vue.js
高山我梦口香糖9 小时前
[react]searchParams转普通对象
开发语言·前端·javascript
black^sugar10 小时前
纯前端实现更新检测
开发语言·前端·javascript
2401_8576009512 小时前
SSM 与 Vue 共筑电脑测评系统:精准洞察电脑世界
前端·javascript·vue.js
2401_8576009512 小时前
数字时代的医疗挂号变革:SSM+Vue 系统设计与实现之道
前端·javascript·vue.js
GDAL12 小时前
vue入门教程:组件透传 Attributes
前端·javascript·vue.js