eletron打包web项目教程(将react打包成桌面端应用程序)

eletron打包web项目教程(将react打包成桌面端应用程序)

1.需要的环境

node -v
npm -v 或 yarn -v

2.安装electron

这里可以采用全局安装或局部安装,包比较大建议采用全局安装

(1)全局安装

npm install electron -g

(2)局部安装

npm install electron -D

3.打包第一个electron应用程序

(1)新建一个文件夹

(2)在文件夹目录执行npm init,生成package.json文件

npm init

(3)安装electron

如果你已经全局安装了,就不用再安装。

如果你是局部安装了,就需要在安装一下

(4)新建index.html,作为我们要打包的第一个electron应用程序页面

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>helloworld</h1>
  </body>
</html>

(5)在项目跟目录新建main.js文件

const { app, BrowserWindow } = require("electron");
const path = require("path");
//通过createWindow方法加载index.html,加载到BrowserWindow实例
const createWindow = () => {
  //创建浏览器窗口
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });
  //加载index.html
  win.loadFile("./index.html");

  // 打开开发工具
  // mainWindow.webContents.openDevTools()
};
// 这段程序将会在 Electron 结束初始化
// 和创建浏览器窗口的时候调用
// 部分 API 在 ready 事件触发后才能使用。
/**
 * 调用createWindow打开窗口,在 Electron 中,只有在 app 模块的 ready 事件被激发后才能创建浏览器窗口。
 *  您可以通过使用 app.whenReady() API来监听此事件。 在whenReady()成功后调用createWindow()。
 */
app.whenReady().then(() => {
  createWindow();

  //macOs没有新窗口打开时,打开一个新窗口
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});
// 除了 macOS 外,当所有窗口都被关闭的时候退出程序。 因此, 通常
// 对应用程序和它们的菜单栏来说应该时刻保持激活状态,
// 直到用户使用 Cmd + Q 明确退出
app.on("window-all-closed", () => {
  // 在 macOS 系统内, 如果没有已开启的应用窗口
  // 点击托盘图标时通常会重新创建一个新窗口
  if (process.platform !== "darwin") app.quit();
});

(6)在项目根目录新建preload.js文件

// 所有的 Node.js API接口 都可以在 preload 进程中被调用.
// 它拥有与Chrome扩展一样的沙盒。
//预加载脚本在加载渲染器进程之前运行,并且可以访问渲染器全局变量(例如window和document)和 Node.js 环境。
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]);
  }
});

(7)修改package.json文件

这里主要修改description描述英文什么都可以

main执向我们新增的main文件

author: 作者 - 英文

不然后面打包可能会报错

{
  "name": "electrondemo",
  "version": "1.0.0",
  "description": "an electron test app",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron-forge start",
    "package": "electron-forge package",
    "make": "electron-forge make"
  },
  "author": "zhuzizhen",
  "license": "ISC",
  "devDependencies": {
    "@electron-forge/cli": "^6.2.1",
    "@electron-forge/maker-deb": "^6.2.1",
    "@electron-forge/maker-rpm": "^6.2.1",
    "@electron-forge/maker-squirrel": "^6.2.1",
    "@electron-forge/maker-zip": "^6.2.1",
    "@electron-forge/plugin-auto-unpack-natives": "^6.2.1",
    "electron": "^25.3.2"
  },
  "dependencies": {
    "electron-squirrel-startup": "^1.0.0"
  }
}

(8)将index.html打包成应用程序

1.将 Electron Forge 添加到您应用的开发依赖中,并使用其"import"命令设置 Forge 的脚手架:
npm install --save-dev @electron-forge/cli
npx electron-forge import

✔ Checking your system
✔ Initializing Git Repository
✔ Writing modified package.json file
✔ Installing dependencies
✔ Writing modified package.json file
✔ Fixing .gitignore

We have ATTEMPTED to convert your app to be in a format that electron-forge understands.

Thanks for using "electron-forge"!!!
2.使用 Forge 的 make 命令来创建可分发的应用程序:
npm run make

> my-electron-app@1.0.0 make /my-electron-app
> electron-forge make

✔ Checking your system
✔ Resolving Forge Config
We need to package your application before we can make it
✔ Preparing to Package Application for arch: x64
✔ Preparing native dependencies
✔ Packaging Application
Making for the following targets: zip
✔ Making for target: zip - On platform: darwin - For arch: x64
2.1make过程中遇到的问题

在这里插入图片描述

2.2解决方法

在这里插入图片描述

npm config set ELECTRON_MIRROR "https://npm.taobao.org/mirrors/electron/"
3.Electron-forge 会创建 out 文件夹,您的软件包将在那里找到:
// Example for macOS
out/
├── out/make/zip/darwin/x64/my-electron-app-darwin-x64-1.0.0.zip
├── ...
└── out/my-electron-app-darwin-x64/my-electron-app.app/Contents/MacOS/my-electron-app

应用程序文件位置:

在这里插入图片描述

应用程序界面:

在这里插入图片描述

eletron将react打包成应用程序

(1)安装electron全局或者局部安装,上面已经有阐述安装方法,这里就不多讲了

(2)在react项目根目录新建main.js文件

需要注意的是这个win.loadFile要加载的是打包后的文件中的index.html

const { app, BrowserWindow } = require('electron')
const path = require('path')
//通过createWindow方法加载index.html,加载到BrowserWindow实例
const createWindow = () => {
  //创建浏览器窗口
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      devTools: true, //是否开启 DevTools
      nodeIntegration: true, //是否集成node
      webSecurity: false //是否禁用同源策略(上线时删除此配置)
    }
  })
  //加载index.html
  win.loadFile('./build/index.html')

  //加载网页
  // win.loadURL('http://localhost:3000')

  // 打开开发工具
  mainWindow.webContents.openDevTools()
}
// 这段程序将会在 Electron 结束初始化
// 和创建浏览器窗口的时候调用
// 部分 API 在 ready 事件触发后才能使用。
/**
 * 调用createWindow打开窗口,在 Electron 中,只有在 app 模块的 ready 事件被激发后才能创建浏览器窗口。
 *  您可以通过使用 app.whenReady() API来监听此事件。 在whenReady()成功后调用createWindow()。
 */
app.whenReady().then(() => {
  createWindow()

  //macOs没有新窗口打开时,打开一个新窗口
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})
// 除了 macOS 外,当所有窗口都被关闭的时候退出程序。 因此, 通常
// 对应用程序和它们的菜单栏来说应该时刻保持激活状态,
// 直到用户使用 Cmd + Q 明确退出
app.on('window-all-closed', () => {
  // 在 macOS 系统内, 如果没有已开启的应用窗口
  // 点击托盘图标时通常会重新创建一个新窗口
  if (process.platform !== 'darwin') app.quit()
})

//解决10.X版本跨域不成功问题(上线删除)
app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors')

(3)新建preload.js文件

// 所有的 Node.js API接口 都可以在 preload 进程中被调用.
// 它拥有与Chrome扩展一样的沙盒。
//预加载脚本在加载渲染器进程之前运行,并且可以访问渲染器全局变量(例如window和document)和 Node.js 环境。
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]);
  }
});

(4)将 Electron Forge 添加到您应用的开发依赖中,并使用其"import"命令设置 Forge 的脚手架:

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

✔ Checking your system
✔ Initializing Git Repository
✔ Writing modified package.json file
✔ Installing dependencies
✔ Writing modified package.json file
✔ Fixing .gitignore

We have ATTEMPTED to convert your app to be in a format that electron-forge understands.

Thanks for using "electron-forge"!!!

这里需要注意,react默认启动项目是start,electron添加package.json中的也是start,会将react项目中的start命令替换掉,所以这里将electron的添加进来的scripts命令加上electron前缀

在这里插入图片描述

(5)运行时查看

1.先执行

npm start

2.再执行,运行时查看,electron应用程序

npm run  electron-start

(6)打包

1.先执行react的打包

npm run build

2.再执行electron的打包

npm run electron-make

3.打包后out目录会有应用程序的exe文件,打开应用程序后

在这里插入图片描述

(7)如果前面接口跨域情况解决

1.在main.js的webPreferences添加

nodeIntegration: true, //是否集成node
webSecurity: false //是否禁用同源策略(上线时删除此配置)

在这里插入图片描述

2.在main.js最后添加

//解决10.X版本跨域不成功问题(上线删除)
app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors')

3.打包后out目录会有应用程序的exe文件,打开应用程序后

在这里插入图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值