电子-如何添加外部文件?

use*_*995 3 javascript node.js electron

我有一个电子应用程序。我尝试使该应用程序打开一个.exe文件。我在根文件夹中创建了一个目录,lib并将.exe文件放置在该目录中。在开发中,使用可以打开文件没有问题__dirname + '/lib/file.exe,但是当我打包应用程序(使用yarn dist)时,它不会打开exe文件,并且libdist文件夹上也没有文件夹。

我尝试编写使用来控制台其默认位置console.log(__dirname),并输出\dist\win-unpacked\resources\app.asa(文件)。

打包应用程序后,如何添加可以访问的外部文件?

dim*_*aqw 12

将以下代码添加到package.json中:

 "build": {
    "extraResources": [
      {
        "from": "./src/extraResources/",
        "to": "extraResources",
        "filter": [
          "**/*"
        ]
      }
    ]
  }
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用

const configFile = path.join(path.dirname(__dirname), 'extraResources','config.json');
Run Code Online (Sandbox Code Playgroud)

我使用以下文件夹结构,该结构允许我以任何方式运行该应用程序。

从项目文件夹: node_modules\.bin\electron.cmd src\main\index.js

来自未包装的来源 dist\win-unpacked\app.exe check-for-update

从已安装的文件夹 C:\Users\user\AppData\Local\Programs\app\app.exe

+-- dist
|   +-- win-unpacked
|      +-- resources
|         +-- extraResources
|            config.json
+-- node_modules
+-- src 
|   +-- extraResources
|      config.json
|      someFile.js
|   +-- main
|      index.js
|   +-- render
|      index.js
Run Code Online (Sandbox Code Playgroud)


小智 9

在那里我找到了一个新的解决方案,在Windows上使用电子打包器,不要在进程结束时将文件添加到资源文件夹中。

所以我将此命令添加到package.json

"build-win": "electron-packager . --platform=win32 --asar --prune --arch=ia32 --extra-resource=./extraResources/documents/QuickStartGuideWN-H1.pdf --extra-resource=./extraResources/MAC_drivers/MacOS10.14/ --icon=assets/alfa_a.ico --out ./dist --overwrite",
Run Code Online (Sandbox Code Playgroud)

现在文件已插入资源文件夹,只需添加

--extra-resource=./extraResources/file
Run Code Online (Sandbox Code Playgroud)


use*_*995 5

通过使用extraResources来解决它。应该在package.json文件的build下声明。

例如:

  1. 在pacakge.json旁边创建一个名为extraResources的新文件夹
  2. 将以下代码添加到您的package.json文件中:

    "build": { "extraResources": ["./extraResources/**"] }

  3. 然后,您可以使用__dirname + '/../extraResources/'主应用程序访问此文件夹中的文件。

  • @americo 您的代码中有一个拼写错误,它应该是“process.resourcesPath”。 (7认同)
  • 这对我有用: ```const path = require('path'); path.join(process.resourcePath, 'extraResources', '文件名'); ```` (3认同)
  • 使用process.resourcesPath而不是__dirname以获得更可靠的跨平台解决方案。 (2认同)