electron如何内嵌应用并打包兼容多平台?

459 阅读1分钟

先看下实现的效果 20240601_114213.gif 什么是Electron?

Electron是一个使用 JavaScript、HTML 和 CSS 构建桌面应用程序的框架。 嵌入 Chromium 和 Node.js 到 二进制的 Electron 允许您保持一个 JavaScript 代码代码库并创建 在Windows上运行的跨平台应用 macOS和Linux——不需要本地开发 经验。

环境搭建

electron开发文档API文档查看和配置node环境请查阅这篇文章

项目初始化

## node 版本 18+

mkdir my-electron-app && cd my-electron-app
npm init

npm install --save-dev electron

## start命令能在开发模式下打开应用
npm start

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

## 打包-electron
npm run make

打包生成的.exe安装文件目录在:
Artifacts available at: I:\yg\XAMPPSERVER\htdocs\demo\my-electron-app\out\make

新建 my-electron/index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello Esther!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
    <h1>Hello Esther!!We are using Node.js让我们每天进步一点,不积跬步无以至千里</h1>
	<iframe
	  id="inlineFrameExample"
	  title="Inline Frame Example"
	  width="1920"
	  height="200"
	  src="http://baidu.com">
	</iframe>
    <iframe
      id="inlineFrameExample"
      title="Inline Frame Example"
      width="1920"
      height="980"
      src="http://192.168.1.253:8091/">
    </iframe>
</body>
</html>

新建 my-electron/main.js

const path = require('node:path')

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  win.loadFile('index.html')
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

新建 my-electron/preload.js

    const replaceText = (selector, text) => {
      const element = document.getElementById(selector)
      if (element) element.innerText = text
    }
  
    for (const type of ['chrome', 'node', 'electron']) {
      replaceText(`${type}-version`, process.versions[type])
    }
  })

如果你是安装我给的项目初始化步骤进行的,那么目录结构应该是这样的

image.png

image.png 在终端 执行 npm start运行 即可看到文章开头展示效果; 既然调试无问题,现在打包 npm run make

image.png

image.png

打开项目根目录下/out/make .exe打包文件 双击即可运行 适合一些无浏览器环境跨平台应用等。

结束!