Fixing the `links out of the package` macOS packaging error

If you are using electron-packager or electron-forge, you might encounter the following error...

Fixing the `links out of the package` macOS packaging error

If you are using electron-packager or electron-forge, you might encounter the following error :

 An unhandled rejection has occurred inside Forge:
Error: /var/folders/24/8k48jl6d249_n_qfxwsl6xvm0000gn/T/electron-packager/darwin-x64/electron-example-darwin-x64-5AYzr2/Electron.app/Contents/Resources/app/node_modules/macos-alias/build/node_gyp_bins/python3: file "../../../../../../../../../../../../../Library/Frameworks/Python.framework/Versions/3.11/bin/python3.11" links out of the package

This error is showing when trying to package an electron application for macOS with Electron Forge. It takes its root in electron-packager and is produced by node-gyp like described in this Github issue.

At this date, there is no fix for this but there is a workaround which we can see mentioned by this user on the repo for electron-packager.

The workaround

As mentioned in the Github issue there is a workaround involving the `afterPrune` hook. This hook is available in electron-packager. If, like us, you are using electron-forge the hook name is `packageAfterPrune`.

It is quite straightforward to use like described in the documentation. You will need to define a function that will be called after the pruning phase. For our specific error, we want to remove the link on python 3. It can be done the following way:

const fs = require('fs')
const path = require('path')

module.exports = {
  hooks: {
    packageAfterPrune: async (forgeConfig, buildPath, electronVersion, platform, arch) => {
      if (platform === 'darwin') {
        console.log("We need to remove the problematic link file on macOS")
        console.log(`Build path ${buildPath}`)
        fs.unlinkSync(path.join(buildPath, 'node_modules/macos-alias/build/node_gyp_bins/python3'))
      }
    }
  },
forge.config.js

For electron-packager you might want to drop the first argument `forgeConfig` as this one is specific to electron-forge.

This is all you need to have it work again!