### Full rebuild example (ESM and CommonJS) Source: https://github.com/electron/rebuild/blob/main/README.md Complete example of rebuilding native modules for Electron 35.1.5. The ESM version uses import.meta.dirname for the build path, while the CommonJS version uses __dirname. Both log success or error messages. ```javascript // ESM import { rebuild } from "@electron/rebuild"; rebuild({ buildPath: import.meta.dirname, electronVersion: "35.1.5", }) .then(() => console.info("Rebuild Successful")) .catch((e) => { console.error("Building modules didn't work!"); console.error(e); }); ``` ```javascript // CommonJS const { rebuild } = require("@electron/rebuild"); rebuild({ buildPath: __dirname, electronVersion: "35.1.5", }) .then(() => console.info("Rebuild Successful")) .catch((e) => { console.error("Building modules didn't work!"); console.error(e); }); ``` -------------------------------- ### Example usage of rebuild with Prebuildify Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuildify.md Example of using the rebuild function with Prebuildify. Activates automatically for modules with vendored prebuilds (e.g., sodium-native, utp-native). The arch option is used for cross-arch prebuild lookup; source builds still require the host arch. ```ts import { rebuild } from '@electron/rebuild'; await rebuild({ buildPath: '/path/to/app', electronVersion: '35.1.5', arch: 'arm64', // cross-arch prebuild lookup for download; source builds still require the host arch }); ``` -------------------------------- ### getNodePreGypRuntimeArgs method Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-pre-gyp.md Returns runtime arguments for node-pre-gyp. Node-API modules (binary.napi_versions present) get no runtime args; ABI-based modules get --runtime=electron --target= --dist-url=. ```ts async getNodePreGypRuntimeArgs(): Promise { const moduleNapiVersions = await this.getSupportedNapiVersions(); if (moduleNapiVersions) { return []; } else { return [ '--runtime=electron', `--target=${this.rebuilder.electronVersion}`, `--dist-url=${this.rebuilder.headerURL}`, ]; } } ``` -------------------------------- ### NodeAPI usage example Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-api.md Example usage of the NodeAPI class: creates an instance with a module name and Electron version, calls getNapiVersion with a list of supported versions, and demonstrates error handling for ensureElectronSupport. ```typescript import { NodeAPI } from './node-api.js'; // internal source import const napi = new NodeAPI('my-native-module', '35.1.5'); const napiVersion = napi.getNapiVersion([3, 4, 5]); console.log(napiVersion); // highest of [3,4,5] supported by Electron 35 try { napi.ensureElectronSupport(); } catch (err) { console.error('Electron too old for Node-API:', (err as Error).message); } ``` -------------------------------- ### Install @electron/rebuild Source: https://github.com/electron/rebuild/blob/main/README.md Install @electron/rebuild as a development dependency. This is the first step to enable rebuilding native Node.js modules against Electron's Node.js version. ```sh npm install --save-dev @electron/rebuild ``` -------------------------------- ### Run from an npm script Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/cli.md Example of an npm script entry that runs electron-rebuild with -f and -w flags. The comment shows the script name 'rebuild'. ```sh # "rebuild": "electron-rebuild -f -w yourmodule" ``` -------------------------------- ### Run electron-rebuild on Unix Source: https://github.com/electron/rebuild/blob/main/README.md Run electron-rebuild after installing a new npm package. This command rebuilds native modules against the Electron Node.js version. ```sh $(npm bin)/electron-rebuild ``` -------------------------------- ### run method Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-pre-gyp.md Spawns node reinstall --fallback-to-build with the target arch/platform, appending --update-binary when the existing binary's arch differs from the target (or the arch cannot be determined). Uses @malept/cross-spawn-promise; rejects when the subprocess exits non-zero. ```ts async run(nodePreGypPath: string): Promise { const redownloadBinary = await this.shouldUpdateBinary(nodePreGypPath); await spawn( process.execPath, [ nodePreGypPath, 'reinstall', '--fallback-to-build', ...(redownloadBinary ? ['--update-binary'] : []), `--arch=${this.rebuilder.arch}`, // fallback build arch `--target_arch=${this.rebuilder.arch}`, // prebuild arch `--target_platform=${this.rebuilder.platform}`, ...(await this.getNodePreGypRuntimeArgs()), ], { cwd: this.modulePath, }, ); } ``` -------------------------------- ### getPrebuildInstallRuntimeArgs method Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Returns runtime arguments for prebuild-install. Node-API modules (binary.napi_versions) download with --runtime=napi --target=; ABI modules use --runtime=electron --target=. ```ts async getPrebuildInstallRuntimeArgs(): Promise { const moduleNapiVersions = await this.getSupportedNapiVersions(); if (moduleNapiVersions) { const napiVersion = this.nodeAPI.getNapiVersion(moduleNapiVersions); return ['--runtime=napi', `--target=${napiVersion}`]; } else { return ['--runtime=electron', `--target=${this.rebuilder.electronVersion}`]; } } ``` -------------------------------- ### run method spawning prebuild-install Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Spawns node --arch --platform --tag-prefix via @malept/cross-spawn-promise. The shim re-executes the real prebuild-install with process.versions.modules overridden to '-1', which tricks prebuild-install into not validating the 1.8.x/8.x Electron ABI collision. ```ts async run(prebuildInstallPath: string): Promise { await spawn( process.execPath, [ path.resolve(import.meta.dirname, '..', `prebuild-shim.js`), prebuildInstallPath, `--arch=${this.rebuilder.arch}`, `--platform=${this.rebuilder.platform}`, `--tag-prefix=${this.rebuilder.prebuildTagPrefix}`, ...(await this.getPrebuildInstallRuntimeArgs()), ], { cwd: this.modulePath, }, ); } ``` -------------------------------- ### Run electron-rebuild to download prebuilt binaries Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Command to run electron-rebuild, which automatically activates PrebuildInstall for dependent modules (e.g., keytar, better-sqlite3 with prebuilds) to download prebuilt binaries rather than compiling. ```sh # Download the correct prebuilt binaries rather than compiling electron-rebuild ``` -------------------------------- ### rebuild(cacheKey) strategy decision Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-rebuilder.md The main rebuild strategy. Unless buildFromSource is set, tries prebuildify, prebuild-install, then node-pre-gyp in order, short-circuiting on the first success; otherwise compiles from source with node-gyp. ```typescript async rebuild(cacheKey: string): Promise { if ( !this.rebuilder.buildFromSource && ((await this.findPrebuildifyModule(cacheKey)) || (await this.findPrebuildInstallModule(cacheKey)) || (await this.findNodePreGypInstallModule(cacheKey))) ) { return true; } return await this.rebuildNodeGypModule(cacheKey); } ``` -------------------------------- ### get buildType(): BuildType getter implementation Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/rebuilder.md Returns BuildType.Debug when debug is true, otherwise BuildType.Release. Used to determine the build configuration for the rebuild process. ```typescript get buildType(): BuildType { return this.debug ? BuildType.Debug : BuildType.Release; } ``` -------------------------------- ### Import rebuild and view options Source: https://github.com/electron/rebuild/blob/main/README.md Shows the basic import and the documented options for the rebuild() function. Use this as a reference for the available options and their defaults when integrating electron-rebuild into your build pipeline. ```javascript import { rebuild } from '@electron/rebuild'; // Public: Rebuilds a node_modules directory with the given Electron version. // // options: Object with the following properties // buildPath - An absolute path to your app's directory. (The directory that contains your node_modules) // electronVersion - The version of Electron to rebuild for // arch (optional) - Default: process.arch - The arch to rebuild for // extraModules (optional) - Default: [] - An array of modules to rebuild as well as the detected modules // onlyModules (optional) - Default: null - An array of modules to rebuild, ONLY these module names will be rebuilt. // The "types" property will be ignored if this option is set. // force (optional) - Default: false - Force a rebuild of modules regardless of their current build state // headerURL (optional) - Default: https://www.electronjs.org/headers - The URL to download Electron header files from // types (optional) - Default: ['prod', 'optional'] - The types of modules to rebuild // mode (optional) - The rebuild mode, either 'sequential' or 'parallel' - Default varies per platform (probably shouldn't mess with this one) // useElectronClang (optional) - Whether to use the clang executable that Electron used when building its binary. This will guarantee compiler compatibility // Returns a Promise indicating whether the operation succeeded or not ``` -------------------------------- ### ModuleWalker class declaration Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-walker.md Class that discovers which installed native modules must be rebuilt by resolving dependency names to real paths and walking node_modules trees, handling symlinks, scoped packages, and nested node_modules. ```ts export class ModuleWalker { buildPath: string; modulesToRebuild: string[]; onlyModules: string[] | null; prodDeps: Set; projectRootPath?: string; realModulePaths: Set; realNodeModulesPaths: Set; types: ModuleType[]; } ``` -------------------------------- ### electron-rebuild CLI usage and options Source: https://github.com/electron/rebuild/blob/main/README.md Shows the full CLI usage and all available options for electron-rebuild. Note that --dist-url can be overridden by the ELECTRON_REBUILD_DIST_URL environment variable, and the default types are 'prod,optional' (devDependencies are not rebuilt unless explicitly included). ```text Usage: electron-rebuild --version [version] --module-dir [path] Options: -v, --version The version of Electron to build against [string] -f, --force Force rebuilding modules, even if we would skip it otherwise [boolean] -a, --arch Override the target architecture to something other than your system's [string] -m, --module-dir The path to the node_modules directory to rebuild [string] -w, --which-module A specific module to build, or comma separated list of modules. Modules will only be rebuilt if they also match the types of dependencies being rebuilt (see --types). [string] -o, --only Only build specified module, or comma separated list of modules. All others are ignored. [string] -e, --electron-prebuilt-dir The path to the prebuilt electron module [string] -d, --dist-url Custom header tarball URL [string] -t, --types The types of dependencies to rebuild. Comma separated list of "prod", "dev" and "optional". Default is "prod,optional" [string] -p, --parallel Rebuild in parallel, this is enabled by default on macOS and Linux [boolean] -s, --sequential Rebuild modules sequentially, this is enabled by default on Windows [boolean] -b, --debug Build debug version of modules [boolean] -j, --jobs Number of parallel compile jobs node-gyp should run (passed as node-gyp --jobs). Defaults to node-gyp's own default. [number] --prebuild-tag-prefix GitHub tag prefix passed to prebuild-install. Default is "v" [string] --force-abi Override the ABI version for the version of Electron you are targeting. Only use when targeting Nightly releases. [number] --use-electron-clang Use the clang executable that Electron used when building its binary. This will guarantee compiler compatibility [boolean] --disable-pre-gyp-copy Disables the pre-gyp copy step [boolean] --build-from-source Skips prebuild download and rebuilds module from source. [boolean] -h, --help Show help [boolean] ``` -------------------------------- ### Library call to rebuild with prebuilds Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Equivalent library call to the electron-rebuild command. It uses plain rebuild() without buildFromSource to download prebuilt binaries. ```ts import { rebuild } from '@electron/rebuild'; await rebuild({ buildPath: '/path/to/app', electronVersion: '35.1.5' }); ``` -------------------------------- ### Force node-pre-gyp reinstall and rebuild Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-pre-gyp.md Runs electron-rebuild with the -o sqlite3 and -f flags to force a fresh node-pre-gyp reinstall and rebuild for the sqlite3 module. The subprocess runs with process.execPath, so the tool must be run on the target platform; platform only affects the --target_platform/--target_arch flags. If findPrebuiltModule returns false, ModuleRebuilder compiles from source, with --fallback-to-build as the first fallback and node-gyp as the second. ```sh # Force a fresh node-pre-gyp reinstall and rebuild electron-rebuild -o sqlite3 -f ``` -------------------------------- ### Rebuild prod, optional, and dev dependencies in parallel with 8 jobs Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/cli.md Use -t to specify dependency types, -p for parallel, and -j to set the number of jobs. ```sh electron-rebuild -t prod,optional,dev -p -j 8 ``` -------------------------------- ### electron-rebuild CLI Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/cli.md Documentation for the electron-rebuild CLI, including usage, all available options, and validation behavior. ```APIDOC ## [CLI] electron-rebuild ### Description Rebuild native Node.js modules against the version of Electron specified by the `--version` flag or the installed `electron` package. The CLI resolves the Electron version, determines the project root, configures all options, prints progress via the lifecycle `modules-found` event, and exits with a status code. ### Usage ``` electron-rebuild --version [version] --module-dir [path] ``` ### Options | Long flag | Short | Type | Description | Maps to option | |---|---|---|---|---| | `--version` | `-v` | string | The version of Electron to build against | `electronVersion` | | `--force` | `-f` | boolean | Force rebuilding modules even if they would otherwise be skipped | `force` | | `--arch` | `-a` | string | Override the target architecture (default: `process.arch`) | `arch` | | `--platform` | — | string | Override the target platform (default: `process.platform`) | `platform` | | `--module-dir` | `-m` | string | Path to the `node_modules` directory to rebuild | `buildPath` | | `--which-module` | `-w` | string | Comma-separated module names to rebuild in addition to detected ones (they still must match `--types`) | `extraModules` | | `--only` | `-o` | string | Comma-separated module names; only these are rebuilt | `onlyModules` | | `--electron-prebuilt-dir` | `-e` | string | Path to a prebuilt `electron` module (its `package.json` version is read when `--version` is absent) | — | | `--dist-url` | `-d` | string | Custom Electron header tarball URL; overrides the `ELECTRON_REBUILD_DIST_URL` env var | `headerURL` | | `--types` | `-t` | string | Comma-separated list of `prod`, `dev`, `optional` (default: `prod,optional`) | `types` | | `--parallel` | `-p` | boolean | Rebuild in parallel (default on macOS and Linux) | `mode: 'parallel'` | | `--sequential` | `-s` | boolean | Rebuild sequentially (default on Windows) | `mode: 'sequential'` | | `--debug` | `-b` | boolean | Build debug versions of modules | `debug` | | `--jobs` | `-j` | number | Parallel compile jobs passed to node-gyp as `--jobs` | `jobs` | | `--prebuild-tag-prefix` | — | string | GitHub tag prefix passed to `prebuild-install` (default: `v`) | `prebuildTagPrefix` | | `--force-abi` | — | number | Override the ABI version (only for Electron nightly releases); must parse as a number | `forceABI` | | `--use-electron-clang` | — | boolean | Use the clang executable Electron used to build its binary | `useElectronClang` | | `--disable-pre-gyp-copy` | — | boolean | Disable the pre-gyp copy step | `disablePreGypCopy` | | `--build-from-source` | — | boolean | Skip prebuild download and compile from source | `buildFromSource` | | `--help` | `-h` | boolean | Print usage and exit 0 | — | ### Validation - `--force-abi` and `--jobs` are converted with `Number()`; a non-numeric value throws `Error("force-abi must be a number")` / `Error("jobs must be a number")`. ``` -------------------------------- ### electron-rebuild CLI usage Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/cli.md Basic CLI usage: specify the Electron version to build against and the path to the node_modules directory to rebuild. ```bash electron-rebuild --version [version] --module-dir [path] ``` -------------------------------- ### rebuild(options: RebuildOptions) Source: https://github.com/electron/rebuild/blob/main/_autodocs/types.md The main entry point for rebuilding native modules against Electron. Accepts a RebuildOptions object and performs the rebuild. ```APIDOC ## rebuild(options: RebuildOptions) ### Description Rebuilds native Node.js modules against a specified Electron version. Accepts a `RebuildOptions` object with fields controlling the build target, module selection, caching, and compilation behavior. ### Parameters #### Request Body (RebuildOptions) - **buildPath** (string) - Required - Path to the directory containing `node_modules`; must be absolute (checked at rebuild time) - **electronVersion** (string) - Required - Electron version to build against - **platform** (NodeJS.Platform) - Optional - Prebuilt-binary target platform (cross-compilation not supported); default `process.platform` - **arch** (string) - Optional - Target rebuild architecture; default `process.arch` - **extraModules** (string[]) - Optional - Additional module names to rebuild; default `[]` - **onlyModules** (string[] | null) - Optional - Only these modules are rebuilt; `types` is ignored when set; default `null` - **force** (boolean) - Optional - Rebuild regardless of build state; default `false` - **headerURL** (string) - Optional - Electron header tarball URL; default `'https://www.electronjs.org/headers'` - **types** (ModuleType[]) - Optional - Dependency sections to rebuild; default `['prod', 'optional']` - **mode** (RebuildMode) - Optional - Sequential or parallel rebuild execution; default `'sequential'` - **debug** (boolean) - Optional - Build Debug instead of Release; default `false` - **useCache** (boolean) - Optional - Hash-based cache (experimental); default `false` - **useElectronClang** (boolean) - Optional - Use Electron's clang toolchain; default `false` - **cachePath** (string) - Optional - Cache directory for `useCache`; default `~/.electron-rebuild-cache` - **prebuildTagPrefix** (string) - Optional - GitHub tag prefix for `prebuild-install`; default `'v'` - **projectRootPath** (string) - Optional - Workspace root (npm/yarn workspaces) - **forceABI** (number) - Optional - ABI override (nightlies only) - **disablePreGypCopy** (boolean) - Optional - Disable copying `.node` files to `bin/`; default `false` - **buildFromSource** (boolean) - Optional - Skip prebuild downloads, always compile; default `false` - **ignoreModules** (string[]) - Optional - Module names to skip - **jobs** (number) - Optional - node-gyp `--jobs` value (node-gyp default when unset) ### Response No explicit return value documented. ``` -------------------------------- ### Inspect NodeGyp args with DEBUG=electron-rebuild Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-gyp.md Run electron-rebuild with DEBUG=electron-rebuild to log the generated node-gyp arguments for a specific native module. The output is logged via d('rebuilding', this.moduleName, 'with args', nodeGypArgs). ```sh DEBUG=electron-rebuild electron-rebuild -o my-native-module ``` -------------------------------- ### Build against a local dist URL and use Electron's clang Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/cli.md Set the ELECTRON_REBUILD_DIST_URL environment variable to a custom header tarball URL and use --use-electron-clang to use Electron's clang. ```sh ELECTRON_REBUILD_DIST_URL=https://example.com/headers electron-rebuild --use-electron-clang ``` -------------------------------- ### prebuiltModuleExists method Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Checks whether a prebuild-install-generated artifact already exists at prebuilds/-/electron-.node. Used by Rebuilder.rebuildModuleAt() to skip a module entirely. ```ts async prebuiltModuleExists(): Promise { return fs.existsSync( path.resolve( this.modulePath, 'prebuilds', `${this.rebuilder.platform}-${this.rebuilder.arch}`, `electron-${this.rebuilder.ABI}.node`, ), ); } ``` -------------------------------- ### Run electron-rebuild on Windows Source: https://github.com/electron/rebuild/blob/main/README.md Run electron-rebuild on Windows. Use this command if you are on Windows. ```sh .\node_modules\.bin\electron-rebuild.cmd ``` -------------------------------- ### Add rebuild script to package.json Source: https://github.com/electron/rebuild/blob/main/README.md Add a rebuild script to package.json. This is useful when you have a good node-gyp config but encounter an error like 'Could not load the Visual C++ component "VCBuild.exe"' on Windows. ```json "scripts": { "rebuild": "electron-rebuild -f -w yourmodule" } ``` -------------------------------- ### getSupportedNapiVersions(): Promise Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-type.md Reads the `binary.napi_versions` field from package.json and returns it as an array of numbers. ```APIDOC ## getSupportedNapiVersions(): Promise ### Description Reads the `binary.napi_versions` field, e.g. `{ "binary": { "napi_versions": [3, 4, 5] } }`, and returns it as `number[]`. ### Method async getSupportedNapiVersions ### Returns Promise - The array of supported NAPI versions, or undefined if not present. ``` -------------------------------- ### rebuild() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/rebuild.md Rebuilds native Node.js modules against Electron's headers. Accepts an options object with buildPath, electronVersion, and optional settings like types, mode, jobs, force, useElectronClang, and headerURL. Returns a promise that resolves when the rebuild completes, and also exposes a lifecycle event emitter for progress tracking. ```APIDOC ## rebuild() ### Description Rebuilds native Node.js modules against Electron's headers. Accepts an options object with buildPath, electronVersion, and optional settings like types, mode, jobs, force, useElectronClang, and headerURL. Returns a promise that resolves when the rebuild completes, and also exposes a lifecycle event emitter for progress tracking. ### Method Function call ### Endpoint `rebuild(options)` ### Parameters #### Options Object - **buildPath** (string) - Required - The path to the app directory containing node_modules. - **electronVersion** (string) - Required - The version of Electron to rebuild against. - **arch** (string) - Optional - The architecture to rebuild for (e.g., 'x64', 'arm64'). - **types** (string[]) - Optional - An array of dependency types to include: 'prod', 'optional', 'dev'. Defaults to ['prod', 'optional']. - **mode** (string) - Optional - The rebuild mode: 'sequential' or 'parallel'. Defaults to 'sequential'. - **jobs** (number) - Optional - The number of parallel jobs to use when mode is 'parallel'. - **force** (boolean) - Optional - If true, forces a rebuild even if not needed. - **useElectronClang** (boolean) - Optional - If true, uses the clang compiler shipped with Electron. - **headerURL** (string) - Optional - The URL to download Electron headers from. Defaults to 'https://www.electronjs.org/headers'. ### Return Value Returns a Promise that resolves when the rebuild completes. The promise also has a `lifecycle` property that is an event emitter with the following events: - **modules-found** - Emitted with an array of native module names found. - **module-done** - Emitted with the name of a module that has been built. ### Example ts import { rebuild } from '@electron/rebuild'; await rebuild({ buildPath: import.meta.dirname, // app dir containing node_modules electronVersion: '35.1.5', }); ### Error Handling If the rebuild fails, the promise rejects with an error. Catch the error to handle failure. ### Integration with Electron Packager Can be used in the `afterCopy` hook of Electron Packager to rebuild native modules after copying the app. js import { packager } from "@electron/packager"; import { rebuild } from "@electron/rebuild"; packager({ afterCopy: [ async ({ buildPath, electronVersion, arch }) => { await rebuild({ buildPath, electronVersion, arch }); }, ], }); ``` -------------------------------- ### Import rebuild and RebuildOptions Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/rebuild.md Import the rebuild function and its options type from the @electron/rebuild package. ```ts import { rebuild, RebuildOptions } from '@electron/rebuild'; ``` -------------------------------- ### cacheModuleState: snapshot and gzip a module directory Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/cache.md Snapshots a module directory, serializes it, gzip-compresses it, and writes it to `/`. The snapshot skips `node_modules` subdirectories and stores file contents verbatim with a SHA-256 hash. Used internally by `ModuleRebuilder.cacheModuleState()`. ```ts export const cacheModuleState = async ( dir: string, cachePath: string, key: string, ): Promise => { const snap = await takeSnapshot(dir); const moduleBuffer = Buffer.from(JSON.stringify(serialize(snap))); const zipped = await new Promise((resolve) => zlib.gzip(moduleBuffer, (_, result) => resolve(result)), ); await fs.promises.mkdir(cachePath, { recursive: true }); await fs.promises.writeFile(path.resolve(cachePath, key), zipped); }; ``` -------------------------------- ### Basic rebuild usage Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/rebuild.md Rebuilds native modules in the app directory. Requires the app directory containing node_modules and the Electron version. ```ts import { rebuild } from '@electron/rebuild'; await rebuild({ buildPath: import.meta.dirname, // app dir containing node_modules electronVersion: '35.1.5', }); ``` -------------------------------- ### Run npm rebuild script Source: https://github.com/electron/rebuild/blob/main/README.md Run the rebuild script defined in package.json. This executes electron-rebuild with the -f and -w flags. ```sh npm run rebuild ``` -------------------------------- ### Rebuild with a specific Electron version Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/cli.md Use the --version flag to specify the Electron version to build against. The value must be passed on the same flag, e.g., electron-rebuild --version 35.1.5. ```sh electron-rebuild --version 35.1.5 ``` -------------------------------- ### PrebuildInstall class declaration Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Defines the PrebuildInstall class that extends NativeModule. It inherits helpers like rebuilder, modulePath, nodeAPI, moduleName, and packageJSON from the base class. ```ts export class PrebuildInstall extends NativeModule { // inherited: rebuilder, modulePath, nodeAPI, moduleName, packageJSON helpers } ``` -------------------------------- ### Enable cache in rebuild() with useCache Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/cache.md Opt-in cache usage via the public API. Set useCache to true and optionally provide a custom cachePath (default is ~/.electron-rebuild-cache). Note that enabling force alongside useCache disables the cache with a console.warn. ```ts import { rebuild } from '@electron/rebuild'; const result = rebuild({ buildPath: '/path/to/app', electronVersion: '35.1.5', useCache: true, // experimental cachePath: '/tmp/my-cache', // default: ~/.electron-rebuild-cache }); result.lifecycle.on('module-done', (name) => console.log(`done: ${name}`)); await result; ``` -------------------------------- ### Expected node-gyp argument shape for Electron 35 on x64 Linux Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-gyp.md Shows the expected argument shape that NodeGyp generates for Electron 35 on x64 Linux. The command runs node-gyp rebuild with --runtime=electron, --target=35.1.5, --arch=x64, --dist-url, --build-from-source, and --silent. ```text node node-gyp rebuild --runtime=electron --target=35.1.5 --arch=x64 --dist-url=https://www.electronjs.org/headers --build-from-source --silent ``` -------------------------------- ### usesTool method Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-pre-gyp.md Checks whether the module (or a @scope/node-pre-gyp fork) is listed in dependencies. Returns true if found. ```ts async usesTool(): Promise { const packageName = await this.findPackageInDependencies('node-pre-gyp'); return !!packageName; } ``` -------------------------------- ### RebuildOptions interface for Electron rebuild configuration Source: https://github.com/electron/rebuild/blob/main/_autodocs/types.md Defines the configuration object for rebuilding native Node modules against Electron. Use this interface to specify the build path, Electron version, and optional overrides for platform, architecture, module selection, caching, and compilation behavior. Note that cross-compilation is not possible; platform and arch overrides only affect downloading prebuilt binaries. ```ts export interface RebuildOptions { /** * The path to the `node_modules` directory to rebuild. */ buildPath: string; /** * The version of Electron to build against. */ electronVersion: string; /** * Override the target platform to something other than the host system platform. * Note: This only applies to downloading prebuilt binaries. **It is not possible to cross-compile native modules.** * * @defaultValue The system `process.platform` value */ platform?: NodeJS.Platform; /** * Override the target rebuild architecture to something other than the host system architecture. * * @defaultValue The system `process.arch` value */ arch?: string; /** * An array of module names to rebuild in addition to detected modules * @default [] */ extraModules?: string[]; /** * An array of module names to rebuild. **Only** these modules will be rebuilt. */ onlyModules?: string[] | null; /** * Force a rebuild of modules regardless of their current build state. */ force?: boolean; /** * URL to download Electron header files from. * @defaultValue `https://www.electronjs.org/headers` */ headerURL?: string; /** * Array of types of dependencies to rebuild. Possible values are `prod`, `dev`, and `optional`. * * @defaultValue `['prod', 'optional']` */ types?: ModuleType[]; /** * Whether to rebuild modules sequentially or in parallel. * * @defaultValue `sequential` */ mode?: RebuildMode; /** * Rebuilds a Debug build of target modules. If this is `false`, a Release build will be generated instead. * * @defaultValue false */ debug?: boolean; /** * Enables hash-based caching to speed up local rebuilds. * * @experimental * @defaultValue false */ useCache?: boolean; /** * Whether to use the `clang` executable that Electron uses when building. * This will guarantee compiler compatibility. * * @defaultValue false */ useElectronClang?: boolean; /** * Sets a custom cache path for the {@link useCache} option. * @experimental * @defaultValue a `.electron-rebuild-cache` folder in the `os.homedir()` directory */ cachePath?: string; /** * GitHub tag prefix passed to `prebuild-install`. * @defaultValue `v` */ prebuildTagPrefix?: string; /** * Path to the root of the project if using npm or yarn workspaces. */ projectRootPath?: string; /** * Override the Application Binary Interface (ABI) version for the version of Electron you are targeting. * Only use when targeting nightly releases. */ forceABI?: number; /** * Disables the copying of `.node` files if not needed. * @defaultValue false */ disablePreGypCopy?: boolean; /** * Skip prebuild download and rebuild module from source. * * @defaultValue false */ buildFromSource?: boolean; /** * Array of module names to ignore during the rebuild process. */ ignoreModules?: string[]; /** * Number of parallel compile jobs `node-gyp` should run, passed through as node-gyp's `--jobs` flag. * * @defaultValue node-gyp's own default when unset */ jobs?: number; } ``` -------------------------------- ### metaData getter Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-rebuilder.md Getter that returns the expected marker contents: --. Uses the arch and ABI from the rebuilder context. ```ts get metaData(): string { return `${this.rebuilder.arch}--${this.rebuilder.ABI}`; } ```