Search code examples
npmelectronproduction-environment

Electon optionally load `electron-debug` on a production built app


I found out that this plugin offers me some usefull utilities but I do not want as a production depedency to my built application thus I installed it as:

npm install --save-dev electron-debug

If I place it like that to my code I assume that my production builds will not run because this depedency does not exist:

require('electron-debug')();

So how I can "optionally" load it and silently suppress any error and continue without any much trouble?

Also here is mentioned :

Only runs when in development, unless overridden by the enabled option.

But if I use --save instead of --save-dev I assume that the dependency will be installed on my production built app as well, a dependency that is only used for debugging, and that kinda sucks.


Solution

  • Your assumption that it won't be included in your production build is correct. So you need a way to know if the module is available.

    In this answer, Stijn de Witt presents a way of doing so:

    // See https://stackoverflow.com/a/33067955, by Stijn de Witt
    function moduleAvailable (name) {
        try {
            require.resolve (name);
            return true;
        } catch (e) {
            // empty
        }
    
        return false;
    }
    
    // Query for your particular module
    if (moduleAvailable ("electron-debug")) require ("electron-debug") ();
    

    I'm not too sure of that, but there is a possibility that it also works with packaged (e.g. by electron-packager) builds of your app.