学习一下Electron,据说很简单

1,019 阅读3分钟

这是我参与更文挑战的第8天,活动详情查看: 更文挑战

项目源码

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端都能用的应用,美滋滋,但请掘友们相信,这只是第一部分🤭,接下来还有很多东西要补上。

项目源码