【前端】Electron 搭建和打包

Electron

1、搭建

1.1、环境

安装 node 和 npm,建议 node 版本更新为最新版本,避免与 electron 版本不兼容。

# 修改源,避免下载 Electron 依赖失败。
npm config set registry https://registry.npmmirror.com

在 C:\Users\username 目录下,修改 .npmrc 文件,添加以下内容

ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/

参考: npx electron-forge import 在国内网络下执行速度慢(甚至无法执行),如何加速? – KyleBlog.cn

1.2、初始化工程

官方指引

mkdir first-electron
cd first-electron
# 初始化工程
npm init

1.3、创建文件

目录结构

first-electron

    ├─index.html
    ├─main.js
    ├─package.json
    └preload.js

index.html

<!--index.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>

main.js

// main.js

// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('node:path')

const 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', () => {
    // 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', () => {
  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.

preload.js

// preload.js

// All the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const dependency of ['chrome', 'node', 'electron']) {
    replaceText(`${dependency}-version`, process.versions[dependency])
  }
})

1.4、运行

在 package.json 声明命令

{
  "scripts": {
    "start": "electron ."
  }
}
# 安装依赖
npm install --save-dev electron

# 运行
npm start

2、打包

官方指引

npm install --save-dev @electron-forge/cli
npx electron-forge import

 # 打包 exe 程序
 npm run package 

打包前,一定要声明 description 和 author

打包后,就会在工程目录下生成 out 目录,里面包含工程的 exe 程序

创作不易,转载请注明出处: 【前端】Electron 搭建和打包
上一篇
下一篇