使用电子构建器构建React Electron应用程序,index.js加载预标记



我有一个应用程序,我现在正试图构建它以进行测试。

我正在使用React和Electron与电子构建器来构建应用程序本身。我不是一个网络开发人员,所以我一直在努力保持基本的东西,只是让一些东西发挥作用。

大约五个小时后,我终于能够让应用程序正确构建并启动,但当它加载index.js(应用程序中的第一个页面(时,它会显示index.js的源代码,而不是呈现内容。在devtools中,所有内容都在一个预标记中。

我已经看了这个线程并尝试过了,但它没有改变任何东西,而且据我所知,我没有使用服务人员。

与devtools一起启动后,实际的Electron窗口显示的内容。

这是main.js中的createWindow函数。我试过对路径名做各种各样的事情,但都没有效果。

function createWindow() {
const startUrl = process.env.ELECTRON_START_URL || url.format({
pathname: path.join(__dirname, '../src/index.js'),
protocol: 'file:',
slashes: true,
});
mainWindow = new BrowserWindow({
width: 800, height: 600, title: "Electron App", webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadURL(startUrl);
mainWindow.on('closed', function () {
mainWindow = null;
});
}

这是我在package.json 中的脚本

"scripts": {
"start": "nf start -p 3000",
"start-electron": "set ELECTRON_START_URL=http://localhost:3000 && electron .",
"react-start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"build-electron": "npm run build && electron-builder build --win"
}

这也是构建部分。老实说,我真的不明白这是什么或是做什么,但经过几个小时的尝试和错误,这就是我现在的处境。

"build": {
"appId": "Test",
"extends": null,
"files": [
"./build/**/*",
"./electron/main.js",
"./src/**/*"
]
}

据我所知,这与Electron启动URL有关,因为当我在createWindow中从const startUrl中删除该URL时,使用npm启动运行该应用程序的操作与构建的Electron应用程序相同,而在使用npm之前,每次都会正常启动该应用程序。

解决方案后编辑:

将内置软件包.json修改为

"build": {
"appId": "Test",
"extends": null,
"files": [
"./build/**/*",
"./electron/main.js",
"./src/**/*"
],
"directories": {
"buildResources": "./public"
}
}    

如果没有这个修改,我还没有测试过它,所以我不确定它是否真的有必要。

起始URL已更改为

const startUrl = process.env.ELECTRON_START_URL || url.format({
pathname: path.join(__dirname, '../build/index.html'),
protocol: 'file:',
slashes: true,
});

您应该用一个html文件来设置它。

const startUrl = process.env.ELECTRON_START_URL || url.format({
pathname: path.join(__dirname, '../src/index.html'),
protocol: 'file:',
slashes: true,
});

您的浏览器窗口应该在生产模式上加载build/index.html

const isDev = require("electron-is-dev");
if (isDev) {
mainWindow.loadURL(process.env.ELECTRON_START_URL);
} else {
mainWindow.loadFile(path.join("build", "index.html"));
}

最新更新