bundling precompiled binary into electron app

后端 未结 6 1692
无人共我
无人共我 2020-11-28 22:21

Is there a good solution on how to include third party pre compiled binaries like imagemagick into an electron app? there are node.js modules but they are all wrappers or na

6条回答
  •  春和景丽
    2020-11-28 22:59

    The above answers helped me figure out how it is done. But there is a much efficient way to distribute binary files.

    Taking cues from tsuriga's answer, here is my code:

    Note: replace or add OS path accordingly.

    • Create a directory ./resources/mac/bin
    • Place you binaries inside this folder
    • Create file ./app/binaries.js and paste the following code:
    'use strict';
    
    import path from 'path';
    import { remote } from 'electron';
    import getPlatform from './get-platform';
    
    const IS_PROD = process.env.NODE_ENV === 'production';
    const root = process.cwd();
    const { isPackaged, getAppPath } = remote.app;
    
    const binariesPath =
      IS_PROD && isPackaged
        ? path.join(path.dirname(getAppPath()), '..', './Resources', './bin')
        : path.join(root, './resources', getPlatform(), './bin');
    
    export const execPath = path.resolve(path.join(binariesPath, './exec-file-name'));
    
    • Create file ./app/get-platform.js and paste the following code:
    'use strict';
    
    import { platform } from 'os';
    
    export default () => {
      switch (platform()) {
        case 'aix':
        case 'freebsd':
        case 'linux':
        case 'openbsd':
        case 'android':
          return 'linux';
        case 'darwin':
        case 'sunos':
          return 'mac';
        case 'win32':
          return 'win';
      }
    };
    
    • Add the following code inside the ./package.json file:
    "build": {
    ....
    
     "extraFiles": [
          {
            "from": "resources/mac/bin",
            "to": "Resources/bin",
            "filter": [
              "**/*"
            ]
          }
        ],
    
    ....
    },
    
    • import binary file path as:
    import { execPath } from './binaries';
    
    #your program code:
    var command = spawn(execPath, arg, {});
    

    Why this is better?

    • The above answers require an additional package called app-root-dir

    • tsuriga's answer doesn't handle the (env=production) build or the pre-packed versions properly. He/she has only taken care of development and post-packaged versions.

提交回复
热议问题