prebuildify

repository·master·Indexed 42 days ago

https://github.com/prebuild/prebuildify

A tool for creating and packaging prebuilt binaries for native Node.js and Electron modules. It allows developers to ship precompiled binaries within npm packages to eliminate the need for users to compile from source. Version 6.0.1 supports Node-API (N-API), custom target runtimes, and integration with node-gyp-build for runtime binary resolution.

Tokens
3.1K
Snippets
7
Records
11
Agent score
52%

What's inside prebuildify

  1. How prebuild tagging works

    master

    Prebuild filenames are composed of tags that include the runtime and either napi or an abi version (e.g., electron.abi40.node).

    To make prebuilds more specific for node-gyp-build to select, you can add additional tags using the --tag-* flags. These tags are auto-detected from the environment. For example, using --napi --tag-uv --tag-armv might produce a filename like node.napi.uv1.armv8.node on an ARM machine.

    When cross-compiling, you can override these values using the specific option (e.g., --armv 7) or as a shortcut via the tag (e.g., --tag-armv 7).

  2. Integrate prebuilds using node-gyp-build

    master

    To ensure your module automatically selects the correct prebuilt binary at runtime, use node-gyp-build.

    1. Install node-gyp-build

    Add node-gyp-build as a dependency in your native module:

    npm install --save node-gyp-build

    2. Configure package.json

    Add node-gyp-build to your install script. This ensures that if a compatible prebuild is not found, the module will fall back to compiling from source using node-gyp rebuild.

    {
      "name": "your-native-module",
      "scripts": {
        "install": "node-gyp-build"
      }
    }

    3. Load the binding in your code

    When requiring your native binding in your entry point (e.g., index.js), use node-gyp-build to resolve the correct binary for the current platform/runtime.

    // Will load a compiled build if present or a prebuild.
    // If no build is found it will throw an exception
    var binding = require('node-gyp-build')(__dirname)
    
    module.exports = binding
    // first install node-gyp-build
    npm install --save node-gyp-build
    
    // In your package.json
    {
      "name": "your-native-module",
      "scripts": {
        "install": "node-gyp-build"
      }
    }
    
    // In your index.js
    var binding = require('node-gyp-build')(__dirname)
    module.exports = binding
  3. Generate prebuilds for native modules

    master

    To package prebuilt binaries, navigate to your native module's directory and run prebuildify.

    By default, prebuilds are stored in the ./prebuilds directory. When publishing your module to npm, ensure you include this folder in your package.

    Build for all Electron and Node.js versions

    Use the --all flag to build for all known targets and --strip to remove symbols from the binaries.

    cd your-native-module
    prebuildify --all --strip

    Build for Node-API (N-API)

    If your module uses Node-API, use the --napi flag. This targets the latest compatible Node.js versions. Note that you should avoid using --all with --napi as it may include incompatible targets.

    prebuildify --napi
    # go to your native module
    cd your-native-module
    # build for all electron/node binary versions and strip out symbols
    prebuildify --all --strip
    # the prebuilds will be stored in ./prebuilds
    ls prebuilds
    
    # prebuild for node-api
    prebuildify --napi
  4. Define build targets

    master

    Targets specify which runtimes and versions you want to generate prebuilds for. You can provide them as simple strings or detailed objects.

    String format: Use the pattern runtime@version. For example:

    • 'node@14.15.0'
    • 'electron@13.0.0'

    Object format:

    { "runtime": "node", "target": "14.15.0" }

    Special Target Modes:

    • All targets: If opts.all is set to true, prebuildify will attempt to build all supported targets defined by node-abi.
    • N-API: If opts.napi is set to true and no targets are provided, it defaults to building the latest supported Node and Electron targets for N-API compatibility.
    // Example targets array
    const targets = [
      'node@16.13.0',
      'electron@14.2.1',
      { runtime: 'node', target: '14.0.0' }
    ];
  5. Understand prebuild filename tagging

    master

    Prebuild files are named using a specific convention to allow loaders to find the correct binary for the current environment. The format is:

    {name}.{tags}.node

    Where tags are joined by dots. The tags included depend on your configuration:

    1. Name: The package name from package.json (or the runtime name if not specified).
    2. ABI: The Node-API/ABI version (e.g., abi107), unless opts.napi is true.
    3. UV: The libuv version (e.g., uv19), if opts.tagUv is enabled.
    4. ARMV: The ARM version (e.g., armv8), if opts.tagArmv is enabled.
    5. LIBC: The C library (e.g., musl or glibc), if opts.tagLibc is enabled.

    Example filename: my-addon.abi107.uv19.musl.node

  6. Configure prebuildify options

    master

    The prebuildify function accepts an opts object to control the build process. Below are the available configuration keys:

    KeyTypeDefaultDescription
    targetsArray<string|object>[]A list of targets to build (e.g., 'node@16.0.0' or { runtime: 'node', target: '16.0.0' }). Required
    archstringos.arch()The target architecture (e.g., 'x64', 'arm64'). Can support multi-arch tuples like 'x64+arm64' (though node-gyp will only receive the first part).
    platformstringos.platform()The target platform (e.g., 'linux', 'darwin', 'win32').
    uvstringuv()The target libuv version (major version).
    armvstringarmv()The target ARM version (e.g., '8').
    libcstring'glibc' or 'musl'The target C library (use 'musl' for Alpine Linux).
    stripbooleanfalseWhether to strip symbols from the .node binary (only works on darwin and linux).
    stripBinstring'strip'The command used to strip symbols.
    nodeGypstringnode-gypThe path to the node-gyp executable.
    shellstring|booleanshell()The shell to use for spawning processes.
    cwdstring'.'The current working directory.
    outstringopts.cwdThe base directory for output.
    debugbooleanfalseWhether to build in debug mode.
    quietbooleanfalseIf true, suppresses node-gyp output.
    preinstallstringundefinedA command to run before each target build.
    postinstallstringundefinedA command to run after each target build.
    artifactsstringundefinedA directory to copy additional artifacts from into the ./prebuilds folder.
    namestringpackage.json.nameThe name used for the prebuild filename tags.
    tagUvstring|booleanundefinedIf true, uses opts.uv. Otherwise, sets the uv tag to the provided string.
    tagArmvstring|booleanundefinedIf true, uses opts.armv. Otherwise, sets the armv tag to the provided string.
    tagLibcstring|booleanundefinedIf true, uses opts.libc. Otherwise, sets the libc tag to the provided string.
    cachestringos.tmpdir()/prebuildifyThe directory used for node-gyp dev files.
  7. Reference prebuildify CLI options

    master

    Options can be provided via the CLI, environment variables, or the programmatic API. CLI options take precedence.

    Target Syntax: A target takes the form of (runtime@)?version (e.g., 8.14.0 or electron@3.0.0). At least one of --target, --all, or --napi must be specified.

    CLIEnvironmentDefaultDescription
    --target -t-Depends.One or more targets
    --all -a-falseBuild all known targets. Takes precedence over --target.
    --napi-trueMake Node-API build(s).
    --electron-compat-falseMake two Node-API builds, one for node and one for Electron.
    --debug-falseMake Debug build(s)
    --archPREBUILD_ARCHos.arch()Target architecture
    --platformPREBUILD_PLATFORMos.platform()Target platform
    --uvPREBUILD_UVprocess.versions.uvMajor libuv version
    --armvPREBUILD_ARMVAuto-detectedNumeric ARM version (e.g. 7)
    --libcPREBUILD_LIBC-glibc, musl on Alpine
    --tag-uv-falseTag prebuild with uv
    --tag-armv-falseTag prebuild with armv
    --tag-libc-falseTag prebuild with libc
    --preinstall--Command to run before build
    --postinstall--Command to run after build
    --shellPREBUILD_SHELL'sh'Shell to spawn commands in
    --artifacts--Directory containing additional files (copied into prebuild dir).
    --stripPREBUILD_STRIPfalseEnable stripping
    --strip-binPREBUILD_STRIP_BIN'strip'Custom strip binary
    --node-gypPREBUILD_NODE_GYP'node-gyp(.cmd)'Custom node-gyp binary
    --quiet-falseSuppress node-gyp output
    --cwd-process.cwd()Working directory
  8. Use the prebuildify function to trigger builds

    master

    The prebuildify function is the primary entry point for programmatically generating prebuilds for native Node.js or Electron modules. It automates the process of running node-gyp rebuild for multiple target runtimes and architectures, stripping symbols, and organizing the resulting .node files into a structured ./prebuilds directory.

    To use it, call prebuildify(opts, cb) where opts is a configuration object and cb is a callback function that receives an error or undefined upon completion.

    const prebuildify = require('prebuildify');
    
    prebuildify({
      targets: ['node@18.0.0', 'electron@25.0.0'],
      arch: 'x64',
      platform: 'linux',
      strip: true
    }, (err) => {
      if (err) console.error(err);
      else console.log('Prebuilds completed successfully!');
    });
  9. Reference prebuildify CLI options and flags

    master

    The following flags are available for the prebuildify command. Note that several flags have aliases for shorter input.

    --name, -n             Module name
    --target, -t           Target(s) to build for (can be multiple)
    --version, -v          Version to tag prebuilds with
    --all, -a               Build for all supported versions
    --napi, --n-api        Build for node-api (default: true)
    --strip-bin           Strip symbols from binaries
    --node-gyp            Use node-gyp
    --tag-uv               Tag with UV version
    --tag-armv             Tag with ARMv version
    --tag-libc             Tag with libc version
    --electron-compat      Enable Electron compatibility
    --cache, -c            Use a cache
    --quiet                Quiet mode (boolean)
    --strip                Strip symbols (boolean)
    --debug                Debug mode (boolean)
  10. Use the prebuildify CLI

    master

    The prebuildify CLI allows you to generate prebuilds for native modules. You can invoke it by passing a target directory as the first argument or by using various flags to configure the build process. By default, it targets node-api (N-API).

    # Basic usage: prebuildify <directory>
    prebuildify ./my-native-module