{"id":16421,"library":"libnpmpack","title":"libnpmpack Programmatic Packing API","description":"libnpmpack provides the programmatic interface for creating tarballs of npm packages, mirroring the functionality of the `npm pack` command-line tool. As an internal library of the npm CLI, it offers a robust and consistent way to prepare packages for distribution, including handling `.npmignore`, `.gitignore`, and package lifecycle scripts during the packing process. The current stable version of the `libnpmpack` package itself is 9.1.5, though it is often consumed as part of the broader npm CLI, which follows its own release schedule (e.g., v10.x and v11.x branches) and sees frequent updates. Its release cadence is tightly coupled with the npm CLI's monorepo development. A key differentiator is that it's the authoritative, low-level implementation for `npm pack`, ensuring compatibility with npm's official packing logic, unlike third-party alternatives which might deviate in edge cases. It focuses on encapsulating the complex logic of package bundling and file inclusion rules.","status":"active","version":"9.1.5","language":"javascript","source_language":"en","source_url":"https://github.com/npm/cli","tags":["javascript"],"install":[{"cmd":"npm install libnpmpack","lang":"bash","label":"npm"},{"cmd":"yarn add libnpmpack","lang":"bash","label":"yarn"},{"cmd":"pnpm add libnpmpack","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core dependency for dependency tree resolution and package graph management, integral to how npm handles package manifests and file inclusion logic.","package":"@npmcli/arborist","optional":false}],"imports":[{"note":"libnpmpack is an ESM-first package, requiring Node.js 20.17+ or 22.9+.","wrong":"const pack = require('libnpmpack')","symbol":"pack","correct":"import { pack } from 'libnpmpack'"},{"note":"Type import for configuring the `pack` function, often found by exploring the package's TypeScript definitions.","symbol":"PackOptions","correct":"import type { PackOptions } from 'libnpmpack'"}],"quickstart":{"code":"import { pack } from 'libnpmpack';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { promises as fs } from 'fs';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst projectRoot = join(__dirname, 'my-test-package');\nconst outputPath = join(__dirname, 'output');\n\nasync function createAndPackPackage() {\n  await fs.mkdir(projectRoot, { recursive: true });\n  await fs.mkdir(outputPath, { recursive: true });\n\n  await fs.writeFile(\n    join(projectRoot, 'package.json'),\n    JSON.stringify({\n      name: 'my-packed-package',\n      version: '1.0.0',\n      main: 'index.js',\n      files: ['index.js', 'data/'],\n      scripts: {\n        test: 'echo \"Error: no test specified\" && exit 1'\n      }\n    }, null, 2)\n  );\n  await fs.writeFile(join(projectRoot, 'index.js'), 'console.log(\"Hello from packed package!\");');\n  await fs.mkdir(join(projectRoot, 'data'), { recursive: true });\n  await fs.writeFile(join(projectRoot, 'data', 'config.txt'), 'some config data');\n  await fs.writeFile(join(projectRoot, '.npmignore'), 'node_modules\\n.git');\n\n  console.log(`Created test package at: ${projectRoot}`);\n\n  try {\n    const tarballs = await pack(projectRoot, {\n      // Optional: Specify a target directory for the tarball\n      // Default is current working directory\n      packDestination: outputPath,\n      // log: console // You can pass a logger object if needed\n    });\n    console.log(`Successfully packed package(s) to:`);\n    tarballs.forEach(tarballPath => console.log(`- ${tarballPath}`));\n  } catch (error) {\n    console.error('Failed to pack package:', error);\n    process.exit(1);\n  } finally {\n    // Clean up created files/directories\n    await fs.rm(projectRoot, { recursive: true, force: true });\n    await fs.rm(outputPath, { recursive: true, force: true });\n    console.log('Cleaned up test directories.');\n  }\n}\n\ncreateAndPackPackage();","lang":"typescript","description":"This quickstart demonstrates how to use `libnpmpack` to programmatically create an npm package tarball from a local directory, including `package.json` and custom files, and then clean up. It simulates a package project and uses the `pack` function with basic options."},"warnings":[{"fix":"Upgrade your Node.js environment to version 20.17.0 or higher, or 22.9.0 or higher.","message":"The `libnpmpack` package, being an internal component of the npm CLI, strictly enforces Node.js engine requirements. As of version 9.x, it requires Node.js `^20.17.0 || >=22.9.0`. Older Node.js versions will result in runtime errors.","severity":"breaking","affected_versions":">=9.0.0"},{"fix":"Pin `libnpmpack` to exact versions in your `package.json` to prevent unexpected behavior with `npm install`, and review npm CLI release notes closely for any changes related to package packing behavior.","message":"As an internal library, `libnpmpack`'s API might not maintain the same level of stability guarantees for external consumers as public-facing npm packages. Minor version bumps of `libnpmpack` or the encompassing `npm` CLI could introduce breaking changes without explicit semver declarations in `libnpmpack` itself, as its primary consumers are other npm CLI components.","severity":"gotcha","affected_versions":">=8.0.0"},{"fix":"Thoroughly test your packing process, inspect the contents of generated `.tgz` files, and consult npm's official documentation on package content for precise control over what gets published.","message":"Understanding npm's file inclusion rules (e.g., how `.npmignore`, `files` array in `package.json`, and `.gitignore` interact) is crucial. Misconfiguration can lead to missing essential files or including unintended ones in the packed tarball.","severity":"gotcha","affected_versions":">=8.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Migrate your project to use ES Module `import` syntax: `import { pack } from 'libnpmpack';`. Ensure your `package.json` specifies `\"type\": \"module\"` or use `.mjs` file extensions for your source files.","cause":"Attempting to import `libnpmpack` using CommonJS `require()` syntax in a Node.js environment where the package is treated as an ES Module.","error":"ERR_REQUIRE_ESM: require() of ES Module ...libnpmpack/index.js from ... not supported."},{"fix":"Verify the import style. For `libnpmpack`, `pack` is a named export: `import { pack } from 'libnpmpack';`.","cause":"Incorrect import statement, often trying to destructure `pack` from a default import when it's a named export, or vice versa.","error":"TypeError: Cannot destructure property 'pack' of 'libnpmpack__default.default' as it is undefined."},{"fix":"Ensure the directory where the tarball is to be created has appropriate write permissions for the user running the Node.js process, or specify a different `packDestination` with adequate permissions.","cause":"The Node.js process does not have sufficient write permissions to create the tarball in the specified `packDestination` or the current working directory.","error":"Error: EACCES: permission denied, open '.../my-package-1.0.0.tgz'"}],"ecosystem":"npm"}