简体   繁体   English

Electron 生成错误的 index.html & renderer.js 文件

[英]Electron build generating wrong index.html & renderer.js file

My electron app is working properly in dev mode( yarn run start ).我的 electron 应用程序在开发模式下正常工作( yarn run start )。 But, when I'm trying to build the app by using " yarn dist " command it's processing without any issue.但是,当我尝试使用“ yarn dist ”命令构建应用程序时,它的处理没有任何问题。 But, when click on the setup file & open the app I can see it's pointing to the wrong index.html & renderer.js .但是,当单击安装文件并打开应用程序时,我可以看到它指向错误的index.html & renderer.js Because of this, I'm getting following error.因此,我收到以下错误。

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

The folder structure of my app is like this -我的应用程序的文件夹结构是这样的 -

在此处输入图像描述

My package.json file structure is -我的package.json文件结构是 -

{
  "name": "electron-webpack-quick-start",
  "version": "1.0.0",
  "license": "MIT",
  "author": {
    "name": "Suresh",
    "email": "suresh@gmail.com",
    "url": "https://example.com"
  },
  "main": "main.js",
  "description": "Test App",
  "scripts": {
    "dev": "electron-webpack dev",
    "compile": "electron-webpack",
    "dist": "yarn compile && electron-builder",
    "dist:dir": "yarn dist --dir -c.compression=store -c.mac.identity=null",
    "pack": "electron-builder --dir",
    "start": "electron .",
    "postinstall": "electron-builder install-app-deps"
  },
  "dependencies": {
    "source-map-support": "^0.5.16"
  },
  "devDependencies": {
    "electron": "^22.0.3",
    "electron-builder": "^22.4.1",
    "electron-webpack": "^2.8.2",
    "webpack": "~4.42.1"
  },
  "build": {
    "appId": "com.example.app",
    "files": [
      "package.json",
      "main.js",
      "preload.js",
      "renderer.js",
      "index.html",
      "node_modules",
      "main.exe"
    ],
    "win": {
      "target": "nsis"
    },
    "dmg": {
      "background": null,
      "backgroundColor": "#ffffff",
      "window": {
        "width": "400",
        "height": "300"
      },
      "contents": [
        {
          "x": 100,
          "y": 100
        },
        {
          "x": 300,
          "y": 100,
          "type": "link",
          "path": "/Applications"
        }
      ]
    },
    "mac": {
      "target": "dmg",
      "category": "public.app-category.utilities"
    },
    "linux": {
      "target": "AppImage",
      "category": "Utility"
    }
  }
}

index.html index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta
      http-equiv="Content-Security-Policy"
      content="default-src 'self'; script-src 'self'"
    />
    <meta
      http-equiv="X-Content-Security-Policy"
      content="default-src 'self'; script-src 'self'"
    />
    <title>Hello from Electron renderer!</title>
  </head>
  <body>
    <h1>Hello from Electron renderer!</h1>
    <p>👋</p>
    <p id="info"></p>
  </body>
  <script src="./renderer.js"></script>
</html>

main.js主程序

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

const createWindow = () => {
    const win = new BrowserWindow({
        width: 1000,
        height: 700,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true
        },
    });

    win.loadFile(path.join(__dirname, 'index.html'));

};

app.whenReady().then(() => {
    let backend;
    backend = path.join(process.cwd(), 'main.exe')
    var execfile = require('child_process').execFile;
    execfile(
        backend,
        {
            windowsHide: true,
        }, (err, stdout, stderr) => {
            if (err) {
                console.log('1.Flask Server Error: ', err);
            } if (stdout) {
                console.log('Flask Server Started: ', stdout);
            } if (stderr) {
                console.log('2.Flask Server Error: ', stderr);
            }
        }
    )

    createWindow();

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    });
});

app.on('window-all-closed', () => {
    exec('taskkill /f /t /im main.exe', (err, stdout, stderr) => {
        if (err) {
            console.log('taskkill error: ', err)
            return;
        }

        console.log('stdout: ', stdout)
        console.log('stderr: ', stderr)
    });

    console.log('application gogin to close...')
    console.log('process.platform: ', process.platform)

    if (process.platform !== 'darwin') {
        app.quit();
    }
});

preload.js预加载.js

const { contextBridge } = require('electron')

contextBridge.exposeInMainWorld('versions', {
    node: () => process.versions.node,
    chrome: () => process.versions.chrome,
    electron: () => process.versions.electron,
    // we can also expose variables, not just functions
})

renderer.js渲染器.js

const information = document.getElementById('info')
information.innerText = `This app is using Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), and Electron (v${versions.electron()})`


function pingServer() {
    fetch('http://127.0.0.1:5000/')
        .then((response) => response.text())
        .then((text) => {
            console.log('Server message: ', text);
            setText("server_msg", text)
        });
}

function setText(id, newvalue) {
    var s = document.getElementById(id);
    s.innerHTML = newvalue;
}

Am I doing anything wrong?我做错了什么吗? Need some help fig.需要一些帮助图。 this out.这个出来

Yeah, I worked through this while developing cross-platform with electron-builder.是的,我在使用 electron-builder 开发跨平台时解决了这个问题。

The issue is with on Intel Mac and Windows, the files and folders are in different directories compared to in dev mode.问题出在 Intel Mac 和 Windows 上,与开发模式相比,文件和文件夹位于不同的目录中。

While I can't tell you how to fix it directly, it's just a matter of getting the relative imports correct, which you can see by comparing things with what's in the win-unpacked folder.虽然我不能告诉您如何直接修复它,但这只是让相关导入正确的问题,您可以通过将内容与 win-unpacked 文件夹中的内容进行比较来查看。

But you can use something like:但是你可以使用类似的东西:

var isDev = process.env.APP_DEV? (process.env.APP_DEV.trim() == "true"): false; In your various javascript and html. And APP_DEV=true in your npm run start or electron. or as you've said yarn run start (as in put it in your packages.json under the start script.在您的各种 javascript 和 html 中。并且APP_DEV=true在您的npm run startelectron.或者正如您所说的yarn run start (如将其放入start脚本下的 packages.json 中。

EDIT: To clarify, to check, look through win-unpacked directory, and you'll see that your __dirname may need to be something else.编辑:为了澄清,检查,查看 win-unpacked 目录,你会发现你的__dirname可能需要是别的东西。

For me I use var dirname = path.join(process.resourcesPath, '..');对我来说,我使用var dirname = path.join(process.resourcesPath, '..'); on windows, and then replace __dirname with dirname在 windows 上,然后将__dirname替换为dirname

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM