当前位置: 首页 > 文档资料 > Electron 中文文档 >

打造你的第一个 Electron 应用

优质
小牛编辑
164浏览
2023-12-01

Electron 可以让你使用纯 JavaScript 调用丰富的原生(操作系统) APIs 来创造桌面应用。 你可以把它看作一个 Node. js 的变体,它专注于桌面应用而不是 Web 服务器端。

这不意味着 Electron 是某个图形用户界面(GUI)库的 JavaScript 版本。 相反,Electron 使用 web 页面作为它的 GUI,所以你能把它看作成一个被 JavaScript 控制的,精简版的 Chromium 浏览器。

注意: 获取该示例的代码仓库: 立即下载并运行 。

从开发的角度来看, Electron application 本质上是一个 Node. js 应用程序。 与 Node.js 模块相同,应用的入口是 package.json 文件。 一个最基本的 Electron 应用一般来说会有如下的目录结构:

your-app/
├── package.json
├── main.js
└── index.html

为你的新Electron应用创建一个新的空文件夹。 打开你的命令行工具,然后从该文件夹运行npm init

npm init

npm 会帮助你创建一个基本的 package.json 文件。 其中的 main 字段所表示的脚本为应用的启动脚本,它将会在主进程中执行。 如下片段是一个 package.json 的示例:

{
  "name": "your-app",
  "version": "0.1.0",
  "main": "main.js"
}

注意:如果 main 字段没有在 package.json 中出现,那么 Electron 将会尝试加载 index.js 文件(就像 Node.js 自身那样)。 如果你实际开发的是一个简单的 Node 应用,那么你需要添加一个 start 脚本来指引 node 去执行当前的 package:

{
  "name": "your-app",
  "version": "0.1.0",
  "main": "main.js",
  "scripts": {
    "start": "node ."
  }
}

把这个 Node 应用转换成一个 Electron 应用也是非常简单的,我们只不过是把 node 运行时替换成了 electron 运行时。

{
  "name": "your-app",
  "version": "0.1.0",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  }
}

Writing Your First Electron App

Electron enables you to create desktop applications with pure JavaScript by providing a runtime with rich native (operating system) APIs. You could see it as a variant of the Node.js runtime that is focused on desktop applications instead of web servers.

This doesn't mean Electron is a JavaScript binding to graphical user interface (GUI) libraries. Instead, Electron uses web pages as its GUI, so you could also see it as a minimal Chromium browser, controlled by JavaScript.

Note: This example is also available as a repository you can download and run immediately.

As far as development is concerned, an Electron application is essentially a Node.js application. The starting point is a package.json that is identical to that of a Node.js module. A most basic Electron app would have the following folder structure:

your-app/
├── package.json
├── main.js
└── index.html

Create a new empty folder for your new Electron application. Open up your command line client and run npm init from that very folder.

npm init

npm will guide you through creating a basic package.json file. The script specified by the main field is the startup script of your app, which will run the main process. An example of your package.json might look like this:

{
  "name": "your-app",
  "version": "0.1.0",
  "main": "main.js"
}

Note: If the main field is not present in package.json, Electron will attempt to load an index.js (as Node.js does). If this was actually a simple Node application, you would add a start script that instructs node to execute the current package:

{
  "name": "your-app",
  "version": "0.1.0",
  "main": "main.js",
  "scripts": {
    "start": "node ."
  }
}

Turning this Node application into an Electron application is quite simple - we merely replace the node runtime with the electron runtime.

{
  "name": "your-app",
  "version": "0.1.0",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  }
}

安装 Electron

现在,您需要安装electron。 我们推荐的安装方法是把它作为您 app 中的开发依赖项,这使您可以在不同的 app 中使用不同的 Electron 版本。 在您的app所在文件夹中运行下面的命令:

npm install --save-dev electron

除此之外,也有其他安装 Electron 的途径。 请咨询安装指南来了解如何用代理、镜像和自定义缓存。

Installing Electron

At this point, you'll need to install electron itself. The recommended way of doing so is to install it as a development dependency in your app, which allows you to work on multiple apps with different Electron versions. To do so, run the following command from your app's directory:

npm install --save-dev electron

Other means for installing Electron exist. Please consult the installation guide to learn about use with proxies, mirrors, and custom caches.

开发一个简易的 Electron

Electron apps 使用JavaScript开发,其工作原理和方法与Node.js 开发相同。 electron模块包含了Electron提供的所有API和功能,引入方法和普通Node.js模块一样:

const electron = require('electron')

electron 模块所提供的功能都是通过命名空间暴露出来的。 比如说: electron.app负责管理Electron 应用程序的生命周期, electron.BrowserWindow类负责创建窗口。 下面是一个简单的main.js文件,它将在应用程序准备就绪后打开一个窗口:

const { app, BrowserWindow } = require('electron')
function createWindow () {   
  // 创建浏览器窗口
  let win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {nodeIntegration: true
    }
  })
  // 加载index.html文件
  win.loadFile('index.html')
}
app.on('ready', createWindow)

您应当在 main.js 中创建窗口,并处理程序中可能遇到的所有系统事件。 下面我们将完善上述例子,添加以下功能:打开开发者工具、处理窗口关闭事件、在macOS用户点击dock上图标时重建窗口,添加后,main. js 就像下面这样:

const { app, BrowserWindow } = require('electron')
// 保持对window对象的全局引用,如果不这么做的话,当JavaScript对象被
// 垃圾回收的时候,window对象将会自动的关闭
let win
function createWindow () {
  // 创建浏览器窗口。
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {nodeIntegration: true
    }
  })
  // 加载index.html文件
  win.loadFile('index.html')
  // 打开开发者工具
  win.webContents.openDevTools()
  // 当 window 被关闭,这个事件会被触发。
  win.on('closed', () => {
    // 取消引用 window 对象,如果你的应用支持多窗口的话,
    // 通常会把多个 window 对象存放在一个数组里面,
    // 与此同时,你应该删除相应的元素。
    win = null
  })
}
// Electron 会在初始化后并准备
// 创建浏览器窗口时,调用这个函数。
// 部分 API 在 ready 事件触发后才能使用。
app.on('ready', createWindow)
// 当全部窗口关闭时退出。
app.on('window-all-closed', () => {
  // 在 macOS 上,除非用户用 Cmd + Q 确定地退出,
  // 否则绝大部分应用及其菜单栏会保持激活。
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
app.on('activate', () => {
  // 在macOS上,当单击dock图标并且没有其他窗口打开时,
  // 通常在应用程序中重新创建一个窗口。
  if (win === null) {
    createWindow()
  }
})
// 在这个文件中,你可以续写应用剩下主进程代码。
// 也可以拆分成几个文件,然后用 require 导入。

最后,创建你想展示的 index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using node <script>document.write(process.versions.node)</script>,
    Chrome <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.
  </body>
</html>

Electron Development in a Nutshell

Electron apps are developed in JavaScript using the same principles and methods found in Node.js development. All APIs and features found in Electron are accessible through the electron module, which can be required like any other Node.js module:

const electron = require('electron')

The electron module exposes features in namespaces. As examples, the lifecycle of the application is managed through electron.app, windows can be created using the electron.BrowserWindow class. A simple main.js file might wait for the application to be ready and open a window:

const { app, BrowserWindow } = require('electron')
function createWindow () {
  // Create the browser window.
  let win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {nodeIntegration: true
    }
  })
  // and load the index.html of the app.
  win.loadFile('index.html')
}
app.on('ready', createWindow)

The main.js should create windows and handle all the system events your application might encounter. A more complete version of the above example might open developer tools, handle the window being closed, or re-create windows on macOS if the user clicks on the app's icon in the dock.

const { app, BrowserWindow } = require('electron')
// 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
function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {nodeIntegration: true
    }
  })
  // and load the index.html of the app.
  win.loadFile('index.html')
  // Open the DevTools.
  win.webContents.openDevTools()
  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}
// 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', createWindow)
// 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()
  }
})
// 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.

Finally the index.html is the web page you want to show:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
    <meta http-equiv="Content-Security-Policy" content="script-src 'self';" />
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using node <script>document.write(process.versions.node)</script>,
    Chrome <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.
  </body>
</html>

启动你的应用

在创建并初始化完成 main.jsindex.htmlpackage.json之后,您就可以在当前工程的根目录执行 npm start 命令来启动刚刚编写好的Electron程序了。

Running Your App

Once you've created your initial main.js, index.html, and package.json files, you can try your app by running npm start from your application's directory.

尝试此例

复制并运行这个库 electron/electron-quick-start

注意:本例需要 Git 和 npm 来运行。

# 克隆这仓库
$ git clone https://github.com/electron/electron-quick-start
# 进入仓库
$ cd electron-quick-start
# 安装依赖库
$ npm install
# 运行应用
$ npm start

启动开发过程的有关模板文件和工具列表, 请参阅模板文件和 CLI 文档 。

Trying this Example

Clone and run the code in this tutorial by using the electron/electron-quick-start repository.

Note: Running this requires Git and npm.

# Clone the repository
$ git clone https://github.com/electron/electron-quick-start
# Go into the repository
$ cd electron-quick-start
# Install dependencies
$ npm install
# Run the app
$ npm start

For a list of boilerplates and tools to kick-start your development process, see the Boilerplates and CLIs documentation.