[Record] electron windows下配置

安装

参考官方的文档[1]
electron的应用本质是一个nodejs的应用,它是基于nodejs而专注于桌面应用开发的工具,因此安装过程是先安装nodejs然后把electron当做nodejs应用的依赖包进行安装。

nodejs下载界面下载最新的nodejs

选择windows下的LTS版本。
在安装过程中的配置界面, 请勾选Node.js runtime、npm package manager和Add to PATH这三个选项。

通过在cmd或者powershell中运行下面命令来检查安装是否成功:

# 下面这行的命令会打印出Node.js的版本信息
node -v

# 下面这行的命令会打印出npm的版本信息
npm -v

全局安装electron库:

npm install electron -g

为了在不同的应用中使用不同的electron版本,需要在每个应用的文件夹中针对性地安装electron库。

创造第一个应用

与 Node.js 模块相同,应用的入口是 package.json 文件。 一个最基本的 Electron 应用一般来说会有如下的目录结构:

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

创建一个空项目文件夹,使用如下命令在文件夹中创建一个package.json(全部默认)

npm init

package.json示例

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

注意:如果 main 字段没有在 package.json 中出现,那么 Electron 将会尝试加载 index.js 文件(就像 Node.js 自身那样)。
然后在文件夹中安装一个electron的版本:

npm install --save-dev electron

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

const electron = require('electron')

下面是一个简单的main.js,为应用程序创建一个窗口

const { app, BrowserWindow } = require('electron')

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

  // 并且为你的应用加载index.html
  win.loadFile('index.html')

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

app.whenReady().then(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', () => {
  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 (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

// 您可以把应用程序其他的流程写在在此文件中
// 代码 也可以拆分成几个文件,然后用 require 导入。

然后一个简单的配套的index.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' 'unsafe-inline';" />
  </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>

然后在项目的文件夹下,通过如下命令启动程序:



  1. https://www.electronjs.org/docs/tutorial/development-environment#setting-up-windows ↩︎

原文地址:https://www.cnblogs.com/immortalBlog/p/13799952.html