CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-dependency-cruiser

Validates and visualizes dependencies with custom rules for JavaScript, TypeScript, and CoffeeScript projects

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

Dependency Cruiser

Dependency 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.

Package Information

  • Package Name: dependency-cruiser
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install dependency-cruiser

Core Imports

import { 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";

Basic Usage

Command Line Interface

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"

Programmatic API

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"
});

Architecture

Dependency Cruiser is built around several key components:

  • Core Analysis Engine: cruise function performs the main dependency analysis, parsing files and building dependency graphs
  • Rule Engine: Validates dependencies against configurable rules for architectural constraints and best practices
  • Format System: format function converts analysis results into various output formats (HTML, DOT, JSON, etc.)
  • Configuration System: Utilities for extracting and processing configuration from various sources (TypeScript, Babel, webpack)
  • Transpiler Integration: Support for multiple transpilers and languages through pluggable parser system
  • Caching System: Performance optimization through intelligent caching of analysis results

Capabilities

Core Analysis

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;
}

Core Analysis

Output Formatting

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;
}

Output Formatting

Configuration Management

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>;

Configuration Management

Rule System

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";

Rule System

Transpiler Support

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;
}

Transpiler Support

Reporter Plugins

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;

Reporter Plugins

CLI Tools

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-html

CLI Tools

Core Types

interface 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;

Install with Tessl CLI

npx tessl i tessl/npm-dependency-cruiser
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/dependency-cruiser@16.10.x
Publish Source
CLI
Badge
tessl/npm-dependency-cruiser badge