Search code examples
electronelectron-forge

Removing package.json or part of it from app in electron-forge


I have started using electron-forge. My package.json is begin added to the final output after making and packaging.

The package.json contains info which I dont want to to be in production. Such as devDependencies or scripts. Putting package.json in forge.config.js ignore list breaks the build.

Is there a way to remove the file or hide ceratin parts of it in the final packaged app?


Solution

  • Use the postPackage hook within your forge.config.js file, like so for example:

    {
        hooks: {
            postPackage: async (forgeConfig, options) => {
                console.info('postPackage() Packages built at:', options.outputPaths);
                if (!(options.outputPaths instanceof Array)) {
                    return;
                }
                const packageDotJson = path.join(options.outputPaths[0], 'resources', 'app', 'package.json');
                const content = fs.readFileSync(packageDotJson);
                const json = JSON.parse(content.toString());
                Object.keys(json).forEach((key) => {
                    switch (key) {
                        case 'name': {
                            break;
                        }
                        case 'version': {
                            break;
                        }
                        case 'main': {
                            break;
                        }
                        case 'author': {
                            break;
                        }
                        case 'description': {
                            break;
                        }
                        default: {
                            delete json[key];
                            break;
                        }
                    }
                });
                fs.writeFileSync(packageDotJson, JSON.stringify(json, null, '\t'));
            },
        }
    }