搭建基于 electron 的 React + Typescript 项目

10 篇文章 0 订阅
4 篇文章 0 订阅

写在前面

出于学习目的,简单搭建了一个关于 electron + react 的项目,记录下搭建过程中的学习过程,还望各位大佬们多多指教~

相关资料:
electron 官方文档
React 官网地址
启动后页面预览

初始化项目

创建 react + typescript 项目

npx create-react-app my-app --typescript

安装 electron 环境

npm i -D electron

创建 electron 入口文件

main.js 文件

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

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true
    }
  })

  /**
   * loadURL 分为两种情况
   *  1.开发环境,指向 react 的开发环境地址
   *  2.生产环境,指向 react build 后的 index.html
   */
  const startUrl =
    process.env.NODE_ENV === 'development'
      ? 'http://localhost:3000'
      :  path.join(__dirname, "/build/index.html");
  mainWindow.loadURL(startUrl);

  // 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(() => {
  const interfaces = require('os').networkInterfaces();
  
  console.log("Mac================" + JSON.stringify(interfaces));
  createWindow()
  
  app.on('activate', function () {
    // 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.
app.on('window-all-closed', function () {
  // 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()
})

// 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.

添加相关脚本

package.json 文件

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start-electron": "cross-env NODE_ENV=development electron .",
    "start-electron-prod": "electron .",
    "build-electron": "electron-packager . myTestApp"
  },
  "main": "main.js",
  "homepage": ".",

项目启动

启动 react 项目

npm run start

启动electron项目

npm run start-electron

而后会自动打开窗口:
在这里插入图片描述
如果想在窗口中打开页面调试工具,可通过:
打开控制台

项目打包

添加 electron-packager 工具

npm i -D electron-packager

打包 react

npm run build

测试是否正常运行:

npm run start-electron-prod

打包 electron 项目

npm run build-electron

而后会生成一个文件夹,便是桌面应用程序的包了,可通过打开 .exe 文件打开程序:
启动项目的程序

其他问题

Require 报错找不到 node 模块时,可尝试:

main.js页面创建浏览器窗口时,添加参数:

nodeIntegration: true

如下:

const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true
    }
  })

结束

只是简单创建个项目,后续有继续学习的话,会进行补充,将内容丰富起来,敬请期待~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的 Electron React 项目实例: 1. 创建一个新的项目文件夹并进入该文件夹: ``` mkdir electron-react-app cd electron-react-app ``` 2. 初始化 npm 项目: ``` npm init -y ``` 3. 安装必要的依赖项: ``` npm install --save electron react react-dom npm install --save-dev electron-builder babel-cli babel-preset-env babel-preset-react webpack webpack-cli webpack-dev-server html-webpack-plugin ``` 4. 创建一个 webpack 配置文件 webpack.config.js: ``` const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.join(__dirname, '/dist'), filename: 'index_bundle.js' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['env', 'react'] } } } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ] }; ``` 5. 创建一个 .babelrc 配置文件: ``` { "presets": ["env", "react"] } ``` 6. 创建一个入口文件 src/index.js: ``` import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render(<h1>Hello, Electron and React!</h1>, document.getElementById('root')); ``` 7. 创建一个 HTML 文件 src/index.html: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Electron React App</title> </head> <body> <div id="root"></div> <script src="index_bundle.js"></script> </body> </html> ``` 8. 创建一个 main.js 文件作为 Electron 主进程文件: ``` const { app, BrowserWindow } = require('electron'); const path = require('path'); const url = require('url'); let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600 }); mainWindow.loadURL(url.format({ pathname: path.join(__dirname, 'dist', 'index.html'), protocol: 'file:', slashes: true })); mainWindow.on('closed', function () { mainWindow = null }); } app.on('ready', createWindow); app.on('window-all-closed', function () { if (process.platform !== 'darwin') { app.quit() } }); app.on('activate', function () { if (mainWindow === null) { createWindow() } }); ``` 9. 在 package.json 中添加以下脚本: ``` "scripts": { "start": "webpack-dev-server --mode development", "build": "webpack --mode production && electron-builder", "electron": "electron ." } ``` 10. 启动项目: ``` npm start ``` 这将启动 Webpack Dev Server 并在浏览器中打开应用程序。在开发期间,每当更改 React 代码时,Webpack Dev Server 会自动重新编译代码并重新加载应用程序。 11. 打包应用程序: ``` npm run build ``` 这将使用 Webpack 和 electron-builder 打包应用程序。打包后的应用程序将在 dist 目录中生成。 12. 运行应用程序: ``` npm run electron ``` 这将启动 Electron 并加载打包后的应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GJWeigege

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值