Electron集成到现有项目的实战

项目源码

Electron怎么玩

真的很简单的,面向百度编程,找寻前辈的足迹,真的很容易的。😄

直接点,开整

首先安装Electron,但是有个坑

坑就是安装卡住了,没事有办法:

npm config set registry=https://registry.npm.taobao.org/
npm config set ELECTRON_MIRROR=http://npm.taobao.org/mirrors/electron/

第一行相信大家都做了。

第二行很关键,如果不设置的话,他会在最后卡住,一直在加载,也不知道搞什么呢。🤦‍

然后在项目的根目录下创建main.js

/* main.js */
const { app, BrowserWindow } = require('electron')
const path = require('path')
const ipc = require('electron').ipcMain
const http = require('http');
const qs = require("qs")
const os = require('os');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
let server;

const initServer = () => {
    server = http.createServer(function (request, response) {
        // 定义了一个post变量,用于暂存请求体的信息
        let post = '';
        // 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
        //当有数据请求时触发
        request.on('data', function (data) {
            post += data;
        });
        // 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
        request.on('end', function () {
            //解析为post对象
            post = JSON.parse(post);
            //将对象转化为字符串
            response.writeHead(200, { 'Content-Type': 'text-plain' });
            response.end('{"status":200}\n');
            mainWindow.webContents.send("flightdata", post)
        });
    }).listen(8124);
}


const createWindow = () => {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        fullscreen: false,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        }
    });

    // and load the index.html of the app.
    mainWindow.loadFile("./build/index.html");

    // mainWindow.maximize()
    mainWindow.removeMenu()
    // mainWindow.webContents.openDevTools()
    mainWindow.webContents.openDevTools({mode:'right'});
    // Emitted when the window is closed.
    mainWindow.on('closed', () => {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
    });
};

const initApp = () => {
    createWindow();
    initServer();
}

// 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.on('ready', initApp);

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On OS X 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();
    }
});

app.on('activate', () => {
    // On OS X 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 (mainWindow === null) {
        createWindow();
    }
});

这里面大部分逻辑你不用考虑,我以后的文章会讲到,而你只需要知道一点就行。

那就是我在这个mian中指定了一个静态网页,巧了!位置就在我们打包文件夹build下🤭。

    // and load the index.html of the app.
    mainWindow.loadFile("./build/index.html");

然后配置package.json

{
    ...
    "main": "main.js",
    "homepage": "./",
    ...
}

分析:

main:配置刚才我们创建的Electron的入口文件main.js
homepage:如果不配置的话,就会。。,em~~~~就会。。算了贴代码吧

    ...
    const publicUrlOrPath = getPublicUrlOrPath(
    process.env.NODE_ENV === 'development',
    require(resolveApp('package.json')).homepage,
    process.env.PUBLIC_URL
    );
    ...

这几句代码就说明webpack会通过package中配置的homepage来设置PUBLIC_URL,so,那么配置homepage就很有必要。
否则,会白屏的!!!

对了还有个大坑,一定注意

如果你用的是react-router提供的BrowserRouter,那你会蒙圈的,因为什么都不会显示,顶多有个你事先安排好的“404”页面,就好像在用浏览器直接访问地址为https://****/index.htmlhistory模式根本不起作用,我猜这是浏览器独门绝技,electron还没支持,我猜的,不一定对。

所以一定要用hash模式

    <HashRouter getUserConfirmation={this.getConfirmation}>
        ...
    </HashRouter>

最后我们再配置一下启动脚本

/* package.json */
 "scripts": {
    ...
    "electron": "electron ."
    ...
  },

至此基本准备就绪,那么打个包,准备发射🚀。

看下效果吧

结语

这么一来,“中用”的Moderate就初步集成了Electron,直接一行命令就能打包成一个pc和mac端都能用的应用,美滋滋,但请掘友们相信,这只是第一部分🤭,接下来还有很多东西要补上。

项目源码

### 解析 Import Error 的常见原因 当遇到 `ImportError: cannot import name 'Generic'` 错误时,通常意味着尝试从模块中导入的对象不存在或无法访问。此问题可能由多种因素引起: - 版本不兼容:不同库之间的版本冲突可能导致此类错误。 - 安装缺失:目标库未正确安装或路径配置有误。 - 导入语句不当:可能存在循环依赖或其他语法层面的问题。 ### 针对 Generic 类型的具体解决方案 对于特定于 `Generic` 的情况,考虑到 Python 中 `Generic` 是 typing 模块的一部分,在处理该类别的 ImportError 时可采取如下措施[^1]: #### 方法一:确认typing模块可用性 确保环境中已安装标准库中的 typing 模块,并且其版本支持所使用的特性。可以通过以下命令验证: ```bash python -c "from typing import Generic; print(Generic)" ``` 如果上述命令执行失败,则可能是由于 Python 或者相关扩展包的版本过低造成的。此时应考虑升级至更高版本的解释器以及对应的开发工具链。 #### 方法二:调整导入方式 有时直接通过顶层命名空间来获取所需组件会更稳定可靠。修改代码以采用这种做法可能会解决问题: ```python from collections.abc import Iterable # 如果是迭代器相关接口 from typing import TypeVar, Protocol # 对于协议和泛型定义 T = TypeVar('T') class MyContainer(Protocol[T]): ... ``` 注意这里并没有显式提到 `Generic` ,而是利用了更为基础的数据结构抽象基类或是其他替代方案实现相同功能[^2]。 #### 方法三:排查环境变量设置 检查系统的 PYTHONPATH 和虚拟环境配置是否正常工作。任何异常都可能导致某些第三方软件包找不到必要的资源文件而引发类似的错误提示。建议清理并重建项目专属的工作区以便排除干扰项的影响。 #### 示例修正后的代码片段 假设原始代码试图这样引入 `Generic` : ```python from some_module import Generic # 可能导致 ImportError ``` 改为遵循官方文档推荐的方式后变为: ```python from typing import Generic # 正确的做法 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值