nypm

repository·main·Indexed 20 days ago

https://github.com/unjs/nypm

A unified package manager interface for Node.js (version 0.6.9) that abstracts npm, pnpm, yarn, Bun, and Deno. It provides a CLI and a programmatic API to detect package managers, manage dependencies, run scripts, and execute packages via dlx, ensuring consistent operations regardless of the underlying tool used in a project.

Tokens
5.8K
Snippets
26
Records
31
Agent score
70%

What's inside nypm

  1. How nypm auto-detects the package manager

    main

    nypm automatically identifies the correct package manager for a project by inspecting the directory (and parent directories) for:

    1. The packageManager field in package.json.
    2. The devEngines.packageManager field in package.json.
    3. Presence of known lockfiles (e.g., package-lock.json, pnpm-lock.yaml, yarn.lock, etc.).
  2. Integrate nypm API into your project

    main

    Import nypm to programmatically manage dependencies and run scripts using a unified API that works across different package managers.

    // ESM import
    import { addDependency } from "nypm";
    
    // or dynamic import
    const { addDependency } = await import("nypm");
  3. Run scripts and execute packages with nypm API

    main

    Use these methods to run lifecycle scripts or download/execute packages using the project's package manager.

    // Run a script defined in package.json
    await runScript('test', options);
    
    // Download and execute a package (similar to npx)
    await dlx('some-package', options);
  4. Generate package manager commands with nypm API

    main

    If you need the raw command strings for a specific package manager instead of executing them directly, use these command generators. They require the package manager identifier (<pm>).

    // Get command to install dependencies
    // Options: { short?: boolean, frozenLockFile?: boolean }
    installDependenciesCommand('pnpm', { frozenLockFile: true });
    
    // Get command to add a dependency
    // Options: { dev?: boolean, global?: boolean, workspace?: boolean, yarnBerry?: boolean, short?: boolean }
    addDependencyCommand('yarn', 'defu', { dev: true });
    
    // Get command to run a script
    // Options: { args?: string[] }
    runScriptCommand('npm', 'build', { args: ['--production'] });
    
    // Get command to download and execute a package (dlx)
    // Options: { args?: string[], short?: boolean, packages?: string[] }
    dlxCommand('bun', 'create-vite', { args: ['my-app'] });
  5. Manage dependencies via nypm API

    main

    Use these methods to manipulate project dependencies programmatically. All methods accept an options object.

    // Add a regular dependency
    await addDependency('defu', options);
    
    // Add a dev dependency
    await addDevDependency('defu', options);
    
    // Remove a dependency
    await removeDependency('defu', options);
    
    // Ensure a dependency is installed
    await ensureDependencyInstalled('defu', options);
    
    // Install all project dependencies
    await installDependencies(options);
    
    // Dedupe dependencies
    // Note: For bun and deno, this removes the lockfile and reinstalls all dependencies.
    await dedupeDependencies(options);
  6. Use the nypm CLI

    main

    You can use nypm via npx to interact with your project's package manager without needing to know which one is being used (npm, pnpm, yarn, bun, or deno).

    # Install dependencies
    npx nypm i
    
    # Add a dependency
    npx nypm add defu
    
    # Remove a dependency
    npx nypm remove defu
  7. Run a package.json script with runScript()

    main

    Executes a script defined in the scripts section of the package.json file using the detected package manager (e.g., npm run <name> or yarn <name>).

    Options:

    • name: The name of the script to run.
    • cwd: The directory to run the command in.
    • env: Additional environment variables to set for the execution.
    • silent: Whether to run the command in silent mode.
    • packageManager: The package manager info to use.
    • dry: If true, the command is not executed.
    • corepack: Whether to use corepack.
    • args: Additional arguments to pass to the script.
    import { runScript } from 'nypm';
    
    await runScript('build', { args: ['--prod'] });
  8. Detect the package manager with detectPackageManager()

    main

    Use detectPackageManager(cwd, options) to identify which package manager is being used in a specific directory or its parent directories.

    Detection follows this priority:

    1. The packageManager field in package.json or deno.json.
    2. The devEngines.packageManager field in package.json.
    3. Presence of known lock files (e.g., package-lock.json, pnpm-lock.yaml, yarn.lock) or configuration files (e.g., pnpm-workspace.yaml, deno.json).
    4. If no files are found, it attempts to detect the manager by inspecting the command used to run the script (e.g., if the path contains pnpm).

    Returns a PackageManager object containing the name, command, lockFile, and potentially warnings, or undefined if no manager is detected.

    import { detectPackageManager } from 'nypm';
    
    const pm = await detectPackageManager(process.cwd());
    if (pm) {
      console.log(`Detected: ${pm.name}`);
    }
  9. Remove dependencies with removeDependency()

    main

    Removes one or more dependencies from the project using the appropriate package manager command (e.g., npm uninstall or yarn remove).

    Options:

    • name: A string or array of strings representing the package names.
    • cwd: The directory to run the command in.
    • silent: Whether to run the command in silent mode.
    • packageManager: The package manager info to use.
    • dev: Whether to remove a dev dependency.
    • global: Whether to run the command in global mode.
    • dry: If true, the command is not executed, but the command and arguments are returned.
    import { removeDependency } from 'nypm';
    
    await removeDependency(['lodash', 'express'], { dev: true });
  10. Dedupe dependencies with dedupeDependencies()

    main

    Attempts to deduplicate dependencies in the project.

    Behavior:

    • For bun and deno, deduplication is not supported and will throw an error.
    • For yarn v1, it runs yarn install.
    • For other supported managers, it runs dedupe.
    • If recreateLockfile is true (or if the package manager doesn't support dedupe), it deletes the existing lockfiles and runs installDependencies().

    Options:

    • cwd: The directory to run the command in.
    • silent: Whether to run the command in silent mode.
    • packageManager: The package manager info to use.
    • dry: If true, the command is not executed.
    • recreateLockfile: Whether to recreate the lockfile instead of deduping.
    import { dedupeDependencies } from 'nypm';
    
    await dedupeDependencies({ recreateLockfile: true });
  11. Add dev dependencies with addDevDependency()

    main

    A convenience wrapper around addDependency() that sets the dev option to true.

    import { addDevDependency } from 'nypm';
    
    await addDevDependency('typescript', { cwd: './' });