A Node.js command-line tool that automates versioning and changelog generation for projects following the Conventional Commits specification.
—
Standard Version provides a Node.js API for integrating automated versioning into build scripts, CI/CD pipelines, and custom automation workflows. The API mirrors the CLI functionality while providing programmatic access to configuration and results.
Core function for executing the standard-version workflow programmatically.
/**
* Execute standard-version workflow with provided configuration
* @param {Object} argv - Configuration options object
* @returns {Promise<void>} Promise that resolves when process completes
* @throws {Error} If version bumping, changelog generation, or git operations fail
*/
async function standardVersion(argv);Usage Examples:
const standardVersion = require('standard-version');
// Basic usage with default configuration
try {
await standardVersion({});
console.log('Release completed successfully');
} catch (error) {
console.error('Release failed:', error.message);
process.exit(1);
}
// Custom configuration
await standardVersion({
releaseAs: 'minor',
infile: 'CHANGELOG.md',
silent: false,
dryRun: true,
scripts: {
prebump: 'npm run test',
postbump: 'npm run build'
}
});
// First release
await standardVersion({
firstRelease: true,
tagPrefix: 'v',
header: '# Release Notes\n\nAll notable changes documented here.\n'
});Load configuration from standard-version configuration files.
/**
* Load configuration from .versionrc files and package.json
* @returns {Object} Merged configuration object from all sources
* @throws {Error} If configuration file contains invalid JSON or structure
*/
function getConfiguration();Usage Examples:
const { getConfiguration } = require('standard-version/lib/configuration');
// Load configuration from files
const config = getConfiguration();
console.log('Loaded config:', config);
// Merge with runtime options
const runtimeOptions = { dryRun: true, silent: false };
const finalConfig = { ...config, ...runtimeOptions };
await standardVersion(finalConfig);Access default configuration values used by standard-version.
/**
* Default configuration object with all standard-version defaults
*/
const defaults = {
infile: 'CHANGELOG.md',
firstRelease: false,
sign: false,
noVerify: false,
commitAll: false,
silent: false,
tagPrefix: 'v',
scripts: {},
skip: {},
dryRun: false,
gitTagFallback: true,
preset: 'conventional-changelog-conventionalcommits',
packageFiles: ['package.json', 'bower.json', 'manifest.json'],
bumpFiles: ['package.json', 'bower.json', 'manifest.json', 'package-lock.json', 'npm-shrinkwrap.json'],
header: '# Changelog\n\nAll notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.\n'
};Usage Examples:
const defaults = require('standard-version/defaults');
// Extend defaults with custom values
const customConfig = {
...defaults,
tagPrefix: 'release-',
infile: 'HISTORY.md',
scripts: {
prebump: 'npm run lint',
postbump: 'npm run build'
}
};
await standardVersion(customConfig);
// Override specific defaults
const config = {
...defaults,
packageFiles: [...defaults.packageFiles, 'VERSION'],
bumpFiles: [...defaults.bumpFiles, 'VERSION']
};Standard Version throws errors for various failure conditions that should be handled programmatically.
/**
* Common error scenarios that may be thrown:
* - No package file found and gitTagFallback disabled
* - Git repository not initialized or not clean
* - Conventional changelog preset not found
* - Custom lifecycle script execution failure
* - File system permission errors
* - Invalid configuration format
*/Usage Examples:
const standardVersion = require('standard-version');
try {
await standardVersion({
gitTagFallback: false,
packageFiles: ['nonexistent.json']
});
} catch (error) {
if (error.message.includes('no package file found')) {
console.error('No valid package files found for version reading');
// Handle missing package files
} else if (error.message.includes('not a git repository')) {
console.error('Standard-version requires a git repository');
// Handle git repository requirement
} else {
console.error('Unexpected error:', error.message);
}
process.exit(1);
}Common patterns for integrating standard-version into build workflows.
CI/CD Integration:
const standardVersion = require('standard-version');
async function release() {
// Ensure clean working directory
const { execSync } = require('child_process');
const status = execSync('git status --porcelain', { encoding: 'utf8' });
if (status.trim()) {
throw new Error('Working directory not clean');
}
// Run tests before release
console.log('Running tests...');
execSync('npm test', { stdio: 'inherit' });
// Execute standard-version
await standardVersion({
silent: false,
scripts: {
prebump: 'npm run build',
postbump: 'npm run package'
}
});
// Push changes and tags
execSync('git push --follow-tags origin main', { stdio: 'inherit' });
}
release().catch(error => {
console.error('Release failed:', error.message);
process.exit(1);
});Custom Release Script:
const standardVersion = require('standard-version');
const { getConfiguration } = require('standard-version/lib/configuration');
async function customRelease(releaseType) {
// Load base configuration
const baseConfig = getConfiguration();
// Add environment-specific overrides
const config = {
...baseConfig,
releaseAs: releaseType,
scripts: {
...baseConfig.scripts,
prebump: 'npm run validate',
precommit: 'npm run security-check',
postcommit: 'npm run deploy-docs'
}
};
if (process.env.CI) {
config.silent = true;
config.noVerify = true;
}
await standardVersion(config);
}
// Export for use in other scripts
module.exports = { customRelease };The programmatic API accepts the same configuration options as the CLI, provided as object properties:
interface StandardVersionOptions {
// Release configuration
releaseAs?: string; // 'major'|'minor'|'patch' or specific version
prerelease?: string | boolean; // Pre-release tag or true for default
firstRelease?: boolean; // Skip version bump for first release
// File configuration
infile?: string; // Changelog file path
packageFiles?: string[]; // Files to read version from
bumpFiles?: string[]; // Files to update with version
// Git configuration
sign?: boolean; // Sign git commit and tag
noVerify?: boolean; // Bypass git hooks
commitAll?: boolean; // Commit all staged changes
tagPrefix?: string; // Git tag prefix
// Behavior configuration
silent?: boolean; // Suppress output
dryRun?: boolean; // Preview mode
gitTagFallback?: boolean; // Use git tags if no package file
// Advanced configuration
scripts?: { // Lifecycle hook scripts
prebump?: string;
postbump?: string;
prechangelog?: string;
postchangelog?: string;
precommit?: string;
postcommit?: string;
pretag?: string;
posttag?: string;
};
skip?: { // Skip specific steps
bump?: boolean;
changelog?: boolean;
commit?: boolean;
tag?: boolean;
};
preset?: string; // Conventional changelog preset
path?: string; // Include only commits under path
header?: string; // Custom changelog header
releaseCommitMessageFormat?: string; // Commit message template
}Standard Version exposes several utility functions that can be useful for advanced programmatic usage and custom integrations.
Get the latest semantic version tag from git repository.
/**
* Get latest semver tag from git repository
* @param {string} [tagPrefix] - Optional tag prefix to filter tags (default: undefined)
* @returns {Promise<string>} Promise resolving to latest version string or '1.0.0' if no tags
*/
async function latestSemverTag(tagPrefix);Usage Examples:
const latestSemverTag = require('standard-version/lib/latest-semver-tag');
// Get latest version with default prefix
const currentVersion = await latestSemverTag();
console.log('Current version:', currentVersion); // "2.1.4"
// Get latest with custom prefix
const currentVersion = await latestSemverTag('release-');
console.log('Current version:', currentVersion); // "2.1.4" (from tag "release-2.1.4")
// Handle no existing tags
const firstVersion = await latestSemverTag();
console.log('First version:', firstVersion); // "1.0.0"Format commit messages with version placeholders.
/**
* Format commit message template with version substitution
* @param {string} rawMsg - Raw commit message template with {{currentTag}} placeholder
* @param {string} newVersion - Version string to substitute
* @returns {string} Formatted commit message
*/
function formatCommitMessage(rawMsg, newVersion);Usage Examples:
const formatCommitMessage = require('standard-version/lib/format-commit-message');
// Basic formatting
const message = formatCommitMessage('chore(release): {{currentTag}}', '1.2.3');
console.log(message); // "chore(release): 1.2.3"
// Custom message template
const customMessage = formatCommitMessage(
'release: bump to {{currentTag}} [skip ci]',
'2.0.0'
);
console.log(customMessage); // "release: bump to 2.0.0 [skip ci]"Safe file writing with consistent behavior and error handling.
/**
* Write content to file with standard-version error handling
* @param {Object} args - Configuration object with silent flag
* @param {string} filePath - Path to file to write
* @param {string} content - Content to write to file
* @returns {void}
* @throws {Error} If file cannot be written
*/
function writeFile(args, filePath, content);Usage Examples:
const writeFile = require('standard-version/lib/write-file');
// Write file with error handling
try {
writeFile(
{ silent: false },
'VERSION',
'1.2.3'
);
console.log('Version file updated');
} catch (error) {
console.error('Failed to write version file:', error.message);
}
// Silent mode
writeFile({ silent: true }, 'RELEASE_INFO.txt', 'Release 1.2.3');Execute external commands and shell scripts with consistent error handling.
/**
* Execute external command with arguments
* @param {Object} args - Configuration object with dryRun and silent flags
* @param {string} cmd - Command to execute
* @param {string[]} cmdArgs - Array of command arguments
* @returns {Promise<void>} Promise that resolves when command completes
* @throws {Error} If command execution fails
*/
async function runExecFile(args, cmd, cmdArgs);
/**
* Execute shell command string
* @param {Object} args - Configuration object with dryRun and silent flags
* @param {string} cmd - Shell command string to execute
* @returns {Promise<void>} Promise that resolves when command completes
* @throws {Error} If command execution fails
*/
async function runExec(args, cmd);Usage Examples:
const runExecFile = require('standard-version/lib/run-execFile');
const runExec = require('standard-version/lib/run-exec');
// Execute command with arguments
try {
await runExecFile(
{ dryRun: false, silent: false },
'git',
['add', 'package.json']
);
console.log('Files staged successfully');
} catch (error) {
console.error('Git add failed:', error.message);
}
// Execute shell command
await runExec({ dryRun: false, silent: false }, 'npm run build');
// Dry run mode
await runExec({ dryRun: true, silent: false }, 'git push'); // Only logs commandLoad and configure conventional changelog presets.
/**
* Load conventional changelog preset with configuration
* @param {Object} args - Configuration object with preset and other changelog options
* @returns {Object} Loaded preset configuration object
* @throws {Error} If preset cannot be loaded or is invalid
*/
function presetLoader(args);Usage Examples:
const presetLoader = require('standard-version/lib/preset-loader');
// Load default preset
const preset = presetLoader({
preset: 'conventional-changelog-conventionalcommits'
});
console.log('Preset loaded:', preset.name);
// Load with custom configuration
const customPreset = presetLoader({
preset: 'conventional-changelog-angular',
types: [
{ type: 'feat', section: 'Features' },
{ type: 'fix', section: 'Bug Fixes' }
]
});Install with Tessl CLI
npx tessl i tessl/npm-standard-version