How can I bundle a precompiled binary with electron

后端 未结 4 1423
执念已碎
执念已碎 2020-12-07 23:27

I am trying to include a precompiled binary with an electron app. I began with electron quick start app and modified my renderer.js file to include this code t

4条回答
  •  天命终不由人
    2020-12-07 23:58

    This is how I would do it:

    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?

    • Most of the answers require an additional package called app-root-dir

    • The original 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.

提交回复
热议问题