当我从 http://localhost:3000
运行 React 构建时,我能够使我的电子构建正常工作。但是,它仅在我启动 localhost 时才有效。
我对电子很陌生,它甚至可能不是我正在寻找的实用程序。有没有办法让我的电子构建运行而无需在后台运行本地主机?
我的目标是将我的 React App 打包并通过可执行文件在其他设备上运行,而无需运行服务器或编码软件。
目前我有:
package.json
{
"homepage": "./",
"main": "./public/main.js",
"build": {
"appId": "test",
"compression": "normal",
"asar": true,
"extends": null,
"files": [
"./public/main.js",
"build/**/*",
"node_modules/**/*"
],
"win": {
"target": "portable"
}
}
}
|---public
| |---index.html
| |---main.js
|---src
| |---App.js
| |---index.js
| |...
main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')
const url = require("url")
function createWindow () {
const win = new BrowserWindow({
width: 1600,
height: 1200
})
win.loadURL(
url.format({
pathname: path.resolve(__dirname, "./index.html"),
protocol: "file",
slashes: true
})
)
win.webContents.openDevTools();
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
如果我启动了 localhost 并且 main.js 的路径名转到 "http://localhost:3000"
一切都按预期工作,React 应用程序会呈现。
当我将路径名指向 path.resolve(__dirname, "./index.html")
时,它会看到 html 并呈现它,但实际上并未呈现任何 React 应用程序。
答案 0 :(得分:0)
Next.js 可以用来实现这一点,它是一个 React 框架,它使用 webpack 将 React 导出为静态文件,无需在后台运行服务器,配置也很少。
在它的 Github 存储库中有一个关于如何将它与电子一起使用的示例,它在开发过程中使用网络服务器,并在生产中作为静态文件导出。 You can check the example here。
如您在示例中所见,React 保存在 renderer
文件夹中,而电子脚本保存在 main
文件夹中。
|--main/
| |--main.js // Your electron main process
| |--preload.js
|--renderer/
| |--components/ // Your React components
| |--pages/
| |--_app.js
| |--index.js
| |--public/
| |--styles/
| |--babel.config.js
|--package.json
当 Next 导出为静态文件时,它会将结果输出到 renderer/out
,此文件夹将包含您在 renderer/pages
中的每个 js 文件的 html 文件,除了 _app.js
,如果您想了解有关 _app.js
click here 的更多信息,它不会有自己的 html 文件,而是会包含在每个页面中。
输出可能是这样的:
|--renderer/out
|--_next/
|--404.html
|--index.html
如果您在导出时在 renderer/pages/welcome.js
中添加了一个文件,则 renderer/out
文件夹中也会有一个 welcome.html
文件。
有了这个,你可以简单地加载 html 文件:
win.loadFile('../renderer/out/index.html');
win.loadFile('../renderer/out/welcome.html');
如果你想使用打字稿,还有一个例子here。
还有give a look to the next documentation。
如果你不想使用 Next,还有一些样板文件和示例,你可能想看看它们使用 webpack:
祝你好运!