Electron:将JS文件而不是HTML文件加载到BrowserWindow

4dc9hkyq  于 2023-05-27  发布在  Electron
关注(0)|答案(2)|浏览(184)

我正在尝试将现有的redux应用程序集成到ElectronJS中。
样板模板在main.js中有以下代码

mainWindow.maximize() 
// and load the index.html of the app.
mainWindow.loadFile('index.html')

我想将index.html更改为React应用的index.js文件。

6g8kf2rb

6g8kf2rb1#

在Electron中,您仍然可以调用mainWindow.loadFile('index.html')
即使您正在为应用的视图编写React代码,所有React应用仍然需要在某个时候调用ReactDOM.render,以将应用附加到某些HTML文件的DOM。
假设你的index.js文件是调用ReactDOM.render()的文件,你需要做的事情与普通的React web应用程序没有太大的不同。

// main.js
// ...
mainWindow.loadFile('index.html')
// ...
<!-- index.html -->
<!-- ... -->
<body>
  <div id="root"></div>
  <script src="../path/to/index.js"></script>
</body>
<!-- ... -->
// index.js

// ...
const app = <MyRootAppComponent/>
ReactDOM.render(app, document.getElementById('root'));
// ...
cngwdvgl

cngwdvgl2#

我为我的全栈Web应用程序(本地)解决了这个问题,其中包括nodejs,express,ejs,mongo等。
步骤1:在package.json中更改您的web应用程序主js文件(mine server.js)

"main": "server.js",

"main": "desktop.js", // or what you want

第2步:将你的app主js文件,server.js,main.js,app.js或其他任何js文件转换成一个模块。

const startServer = async function () {
...
}
startServer();

const startServer = async function () {
...
}
//startServer();
module.export = startServer;

步骤3:在app目录中创建desktop.js文件。

步骤4:在desktop.js中创建电子应用程序

const { app, BrowserWindow } = require('electron');

function createWindow() {
    const mainWindow = new BrowserWindow({
        // window options
        title: 'Garaj Portal',
    });
}
app.whenReady().then(createWindow);

步骤5:主要思想是在加载任何东西之前运行server.js文件。之后,只需加载URL,如http:localhost:3000

const { app, BrowserWindow } = require('electron');
const startServer = require('./server');

async function createWindow() {
    const mainWindow = new BrowserWindow({
       ...
    });

    await startServer();
    mainWindow.loadURL('http://localhost:27027')
}

相关问题