Validates and visualizes dependencies with custom rules for JavaScript, TypeScript, and CoffeeScript projects
npx @tessl/cli install tessl/npm-dependency-cruiser@16.10.0Dependency Cruiser is a comprehensive static analysis tool that validates and visualizes dependencies with custom rules for JavaScript, TypeScript, CoffeeScript, and other transpiled languages. It provides both programmatic API and command-line interfaces for dependency analysis, rule validation, and various output formats including visual graphs and detailed reports.
npm install dependency-cruiserimport { cruise, format } from "dependency-cruiser";For CommonJS:
const { cruise, format } = require("dependency-cruiser");Individual utilities:
import {
allExtensions,
getAvailableTranspilers
} from "dependency-cruiser";
// Configuration utilities
import extractDepcruiseConfig from "dependency-cruiser/config-utl/extract-depcruise-config";
import extractBabelConfig from "dependency-cruiser/config-utl/extract-babel-config";
import extractTsConfig from "dependency-cruiser/config-utl/extract-ts-config";
import extractWebpackResolveConfig from "dependency-cruiser/config-utl/extract-webpack-resolve-config";Dependency Cruiser is primarily used as a command-line tool:
# Initialize configuration
npx depcruise --init
# Analyze dependencies with validation
npx depcruise src --config .dependency-cruiser.js
# Generate visual dependency graph
npx depcruise src --output-type dot | dot -T svg > deps.svg
# Focus on specific modules and their neighbors
npx depcruise src --focus "src/main" --output-type html
# Generate error report with detailed information
npx depcruise src --output-type err-long --include-only "^src"import { cruise, format } from "dependency-cruiser";
// Basic dependency analysis
const result = await cruise(
["src", "test"], // files/directories to analyze
{
validate: true,
ruleSet: {
forbidden: [
{
name: "no-circular",
from: {},
to: { circular: true }
}
]
},
outputType: "json"
}
);
console.log(`Analyzed ${result.output.summary.totalCruised} modules`);
console.log(`Found ${result.output.summary.error} errors`);
// Format results for different output
const htmlReport = await format(result.output, {
outputType: "html"
});Dependency Cruiser is built around several key components:
cruise function performs the main dependency analysis, parsing files and building dependency graphsformat function converts analysis results into various output formats (HTML, DOT, JSON, etc.)Main dependency analysis functionality that examines project files and builds comprehensive dependency graphs with rule validation.
function cruise(
fileAndDirectoryArray: string[],
cruiseOptions?: ICruiseOptions,
resolveOptions?: Partial<IResolveOptions>,
transpileOptions?: ITranspileOptions
): Promise<IReporterOutput>;
interface IReporterOutput {
output: ICruiseResult | string;
exitCode: number;
}Format analysis results into various output types including HTML reports, visual graphs, and structured data formats.
function format(
result: ICruiseResult,
formatOptions: IFormatOptions
): Promise<IReporterOutput>;
interface IFormatOptions {
outputType?: OutputType;
exclude?: string | string[] | IExcludeType;
includeOnly?: string | string[] | IIncludeOnlyType;
focus?: string | string[] | IFocusType;
reaches?: string | string[] | IReachesType;
collapse?: string | number;
prefix?: string;
}Extract and process configuration from various sources including dependency-cruiser configs, TypeScript, Babel, and webpack configurations.
function extractDepcruiseConfig(
configFileName: string,
alreadyVisited?: Set<string>,
baseDirectory?: string
): Promise<IConfiguration>;
function extractBabelConfig(babelConfigFileName: string): Promise<object>;
function extractTsConfig(tsConfigFileName: string): Promise<object>;
function extractWebpackResolveConfig(
webpackConfigFileName: string,
env?: WebpackEnvType,
argv?: any
): Promise<object>;
function extractDepcruiseOptions(configFileName: string): Promise<ICruiseOptions>;Comprehensive rule system for validating dependencies against architectural constraints, circular dependencies, and custom business rules.
interface IFlattenedRuleSet {
forbidden?: IRegularForbiddenRuleType[];
allowed?: IRegularAllowedRuleType[];
required?: IRegularRequiredRuleType[];
allowedSeverity?: SeverityType;
options?: IRuleSetOptions;
}
type SeverityType = "error" | "warn" | "info" | "ignore";Access information about supported transpilers and file extensions, with runtime availability checking.
function getAvailableTranspilers(): IAvailableTranspiler[];
const allExtensions: IAvailableExtension[];
interface IAvailableTranspiler {
name: string;
version: string;
available: boolean;
currentVersion: string;
}
interface IAvailableExtension {
extension: string;
available: boolean;
}Built-in reporter plugins for generating statistics and custom output formats.
// Sample statistics reporter plugin
import statsPlugin from "dependency-cruiser/sample-reporter-plugin";
// Mermaid diagram reporter plugin
import mermaidPlugin from "dependency-cruiser/mermaid-reporter-plugin";
// 3D visualization reporter plugin
import threeDPlugin from "dependency-cruiser/sample-3d-reporter-plugin";
type ReporterPlugin = (cruiseResult: ICruiseResult) => IReporterOutput;Command-line tools for dependency analysis, reporting, and baseline management.
# Main analysis tool
depcruise [options] <files-or-directories>
# Format existing results
depcruise-fmt [options] <cruise-result-file>
# Generate baseline of known violations
depcruise-baseline [options] <files-or-directories>
# Wrap stream output in HTML
depcruise-wrap-stream-in-htmlinterface ICruiseOptions {
validate?: boolean;
ruleSet?: IFlattenedRuleSet;
outputType?: OutputType;
exclude?: string | string[] | IExcludeType;
includeOnly?: string | string[] | IIncludeOnlyType;
focus?: string | string[] | IFocusType;
reaches?: string | string[] | IReachesType;
maxDepth?: number | string;
moduleSystems?: ModuleSystemType[];
tsPreCompilationDeps?: boolean | "specify";
cache?: boolean | string | Partial<ICacheOptions>;
metrics?: boolean;
progress?: { type: ProgressType; maximumLevel?: number };
}
interface ICruiseResult {
modules: IModule[];
folders?: IFolder[];
summary: ISummary;
revisionData?: IRevisionData;
}
interface IModule {
source: string;
valid: boolean;
dependencies: IDependency[];
dependents: string[];
coreModule?: boolean;
couldNotResolve?: boolean;
dependencyTypes?: DependencyType[];
instability?: number;
orphan?: boolean;
reachable?: IReachable[];
reaches?: IReaches[];
rules?: IRuleSummary[];
}
interface IDependency {
module: string;
resolved: string;
circular: boolean;
dynamic: boolean;
followable: boolean;
valid: boolean;
coreModule: boolean;
couldNotResolve: boolean;
dependencyTypes: DependencyType[];
moduleSystem: ModuleSystemType;
rules?: IRuleSummary[];
}
type OutputType =
| "json" | "html" | "dot" | "cdot" | "archi" | "ddot"
| "fdot" | "flat" | "csv" | "err" | "err-long" | "err-html"
| "teamcity" | "azure-devops" | "anon" | "text" | "metrics"
| "markdown" | "mermaid" | "d2" | "x-dot-webpage" | "baseline"
| "null" | string;
type ModuleSystemType = "cjs" | "amd" | "es6" | "tsd";
type DependencyType =
| "local" | "core" | "npm" | "npm-dev" | "npm-optional"
| "npm-peer" | "dynamic-import" | "type-only" | "deprecated"
| string;