使用 electron 时,若引入外部文件,默认是将文件打包进 app.asar 的,但有时我们不想要将其压缩进app.asar,此时可以将自定义文件、文件夹打包进 app 文件夹中,需要进行如下步骤:
注意:本文使用 Electron-builder 作为构建工具。
resources/app 文件夹下,主要配置如下:在 package.json 中的 build 配置下增加以下配置:
json    "asar": false,
    "extraResources": [
      {
        "from": "resources/dist/",
        "to": "app/dist/"
      },
      {
        "from": "resources/config/",
        "to": "app/config/"
      },
      {
        "from": "resources/sql/",
        "to": "app/sql/"
      },
      {
        "from": "resources/cashbook-server.exe",
        "to": "app/cashbook-server.exe"
      }
    ]
配置说明:
"asar": false:将压缩为 asar 改为否,即不压缩。resources/dist/:指定当前目录下的 resources/dist/ 文件夹。和 package.json 同级,开发者自行创建的 resources/dist/ 文件夹。app/dist/:打包时,将指定的文件夹内容拷贝到resouorces/app/dist文件夹。像上面一样配置好,将内容拷贝到打包后的文件夹后,要想在 main.js 的代码中调用到拷贝后的文件,建议使用 path.join() 来拼接路径,如:
js// 加载页面
let indexPath = path.join(__dirname, "dist/index.html");
win.loadFile(indexPath);
总结:从 path.join(__dirname, "dist/index.html"); 这行代码,结合上面示例中的配置 "to": "app/dist/"可以看出,__dirname 默认包含了 app 这个文件夹节点,所以我们只需要拼接上 "dist/index.html" 即可。这也是在配置中,都要有 app 这个文件夹节点的原因!
resources 的文件夹。myFolder)复制到 resources 文件夹中。resources 文件夹的绝对路径:jsconst path = require('path');
const resourcesPath = path.join(__dirname, 'resources');
jsconst { BrowserWindow } = require('electron');
const path = require('path');
const resourcesPath = path.join(__dirname, 'resources');
const mainWindow = new BrowserWindow({
  width: 800,
  height: 600,
  webPreferences: {
    preload: path.join(resourcesPath, 'preload.js')
  }
});
这样可以确保在渲染进程中可以使用require来获取myFolder文件夹中的文件。
jsconst path = require('path');
const { remote } = require('electron');
const resourcesPath = remote.app.getPath('userData');
const myFolderPath = path.join(resourcesPath, 'myFolder');
这样可以确保在渲染进程中可以使用node.js的fs模块访问myFolder文件夹中的文件。
js"build": {
  "asarUnpack": [
    "resources/myFolder"
  ]
}
这样可以确保在打包应用程序时,myFolder文件夹不会被打包进app.asar,而是作为一个独立的文件夹存在。
如果你觉得本文对你有用,想要给作者一些赞助,可以动动小手点击下方广告给予支持,万分感谢~
您的每次点击都能给予作者更多分享的动力!请无情点击吧:
本文作者:DingDangDog
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!