Utility library for detecting whether JavaScript code is running within npm or yarn script execution context through environment variable checks
npx @tessl/cli install tessl/npm-is-npm@6.0.0Check if your code is running as an npm or yarn script. This package provides three boolean constants that detect the package manager execution context by analyzing environment variables set by npm and yarn.
npm install is-npmimport { isNpm, isYarn, isNpmOrYarn } from "is-npm";For TypeScript:
import { isNpm, isYarn, isNpmOrYarn } from "is-npm";import { isNpmOrYarn, isNpm, isYarn } from "is-npm";
// Check if running under any package manager
if (isNpmOrYarn) {
console.log("Running as an npm or yarn script!");
}
// Check specifically for npm
if (isNpm) {
console.log("Running as an npm script!");
}
// Check specifically for yarn
if (isYarn) {
console.log("Running as a yarn script!");
}
// Conditional logic based on execution context
console.table({ isNpmOrYarn, isNpm, isYarn });Provides boolean constants to detect the current package manager execution context.
/**
* Check if code is running as an npm script
* Detects both npm 6 (via user agent) and npm 7+ (via package.json path)
*/
export const isNpm: boolean;
/**
* Check if code is running as a yarn script
* Detects yarn by checking the user agent environment variable
*/
export const isYarn: boolean;
/**
* Check if code is running as either npm or yarn script
* Logical OR combination of isNpm and isYarn
*/
export const isNpmOrYarn: boolean;The package uses environment variables set by npm and yarn during script execution:
process.env.npm_config_user_agent (npm 6) and process.env.npm_package_json (npm 7+)process.env.npm_config_user_agent starting with "yarn"Common use cases for package manager detection:
import { isNpmOrYarn } from "is-npm";
// Conditional behavior in build scripts
if (isNpmOrYarn) {
// Code runs only when executed via package manager
console.log("Running in development mode");
} else {
// Code runs when executed directly with node
console.log("Running in production mode");
}import { isNpm, isYarn } from "is-npm";
// Package manager specific logic
if (isNpm) {
console.log("Using npm-specific configuration");
} else if (isYarn) {
console.log("Using yarn-specific configuration");
} else {
console.log("Running outside package manager context");
}The package relies on these environment variables automatically set by package managers:
npm_config_user_agent: Contains package manager name and version (both npm and yarn)npm_package_json: Contains path to package.json (npm 7+ only)These variables are automatically available when scripts are executed via npm run or yarn run commands.