3

我有一个 Electron (1.7.10) 应用程序报告它在我的 ASAR 中找不到 7 个 PNG 文件中的 5 个。所有 7 个 PNG 都在同一个文件夹中,其中 2 个可以正常显示在屏幕上。其他 5 个报告net::ERR_FILE_NOT_FOUND

img 标签的所有 src 属性都是动态生成的,并使用相对路径 ( assets/images/MyImage.png)。如果我提取 ASAR,我可以在正确的文件夹中看到文件(由 src 属性引用)。

如果我使用控制台将浏览器的位置设置为图像之一 ( document.location.href = "file:///path/to/app.asar/dist/assets/images/MyImage.png"),我会得到相同的结果 - 7 个中的 2 个显示正常。

在打包我的应用程序(使用电子生成器)之前,所有图像都正确显示。

4

3 回答 3

1

我没有评估其他答案,但对于我的特殊情况,一个非常有效的解决方案。我不相信这是有据可查的,所以人们仍然遇到这个问题可能是相当普遍的。对于我的详细信息,此处确定了相关问题和解决方案。

要解决此问题,请添加<base href='./' />到 index.html(或托管 SPA 的任何起始 html 文件)。这是我的一个完整示例:

索引.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <base href="./" />
        <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="theme-color" content="#000000" />
        <meta
            name="description"
            content="Web site created using create-react-app"
        />
        <meta
            http-equiv="Content-Security-Policy"
            content="script-src 'Self' 'unsafe-inline';"
        />
        <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
        <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
        <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
        <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->

        <title>React App</title>
    </head>
    <body>
        <noscript>You need to enable JavaScript to run this app.</noscript>
        <div id="root"></div>
    </body>
</html>
于 2021-09-21T14:57:36.777 回答
1

让我猜猜,你正在使用 react-router 和 BrowserRouter 构建一个 react SPA?

如果是这样,请改用 HashRouter。Electron 默认情况下不使用 SPA 的路由,因为 SPA 路由会发生变化,但资源路径始终是相对于 index.html 的。

于 2019-06-10T13:52:39.377 回答
0
const path = require('path');

path.join(__dirname, 'assets/images/MyImage.png');
于 2018-04-06T05:32:22.930 回答