使用 electron-builder 构建 React-Electron 应用程序,index.js 在 pre 标签内加载

Building a React-Electron app using electron-builder, index.js loads inside pre tags

我有一个应用程序,我正在尝试构建以分发以进行测试。

我正在使用 React 和 Electron 以及 electron-builder 来构建应用程序本身。我不是网络开发人员,所以我一直在努力保持基本的东西,只是让一些东西起作用。

大约五个小时后,我终于能够让应用程序稍微正确地构建并启动,但是当它加载 index.js(应用程序的第一页)时,它会显示 [=44= 的源代码] 而不是渲染内容。在 devtools 中,所有内容都在 pre 标签内。

我已经看过 并尝试过,但它没有改变任何东西,据我所知我没有使用服务工作者。

What the actual Electron window displays after launching with the devtools alongside.

这是 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 中删除它时,运行 使用 npm start 的应用程序做了与构建的 Electron 应用程序相同,而在使用 npm 之前每次都会正常启动应用程序。

解决后编辑:

将 package.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,
    });

您的浏览器 window 应该在生产模式下加载 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"));
    }