Dependency Cruiser

17.3.10 · active · verified Sun Apr 19

Dependency Cruiser is a static analysis tool for validating and visualizing dependencies in JavaScript, TypeScript, and CoffeeScript projects, supporting various module systems including ES6, CommonJS, and AMD. Currently at version 17.3.10, the project demonstrates an active release cadence with frequent maintenance and feature updates. Key differentiators include its ability to define and enforce custom architectural rules, detect issues like circular dependencies or missing `package.json` entries, and generate highly customizable dependency graphs in multiple formats such as DOT, SVG, Mermaid, JSON, HTML, or plain text. It offers both a command-line interface for quick analysis and reporting, and a programmatic API for deeper integration into build processes or custom tooling.

Common errors

Warnings

Install

Imports

Quickstart

Installs Dependency Cruiser, generates a basic configuration, then demonstrates CLI usage for visual graph generation and programmatic API usage for rule validation in a TypeScript project.

npm install --save-dev dependency-cruiser
npx depcruise --init
# Answer prompts to generate .dependency-cruiser.js configuration

# Run analysis and generate an SVG graph using Graphviz dot tool
npx depcruise src --include-only "^src" --output-type dot | dot -T svg > dependency-graph.svg

# For programmatic use, e.g., in a CI/CD pipeline or custom script:
// my-analysis.ts
import { cruise, format } from 'dependency-cruiser';
import type { IConfiguration, ICruiseResult } from 'dependency-cruiser';

const config: IConfiguration = {
  forbidden: [
    {
      name: 'no-circular',
      comment: 'This dependency is part of a circular relationship.',
      severity: 'warn',
      from: {}, to: { circular: true }
    },
    {
      name: 'no-internal-to-external',
      comment: 'Don\'t allow internal code to depend on external libraries outside of an adapter layer.',
      severity: 'error',
      from: { path: '^src/(?!adapters)' },
      to: { dependencyTypes: ['npm', 'npm-dev'] }
    }
  ],
  options: {
    // Configure to resolve TypeScript paths, etc.
    tsPreCompilationDeps: true,
    doNotFollow: {
      path: 'node_modules'
    },
    moduleSystems: ['es6', 'cjs'],
  }
};

async function analyzeDependencies() {
  try {
    const { output, exitCode } = await cruise(
      ['src'], // Files or globs to cruise
      config
    ) as ICruiseResult;

    if (exitCode !== 0) {
      console.error('Dependency violations found:\n', output);
    } else {
      console.log('No dependency violations found.');
    }

    // Example of using format for custom reporting (e.g., HTML)
    // const htmlReport = format(output, { outputType: 'html' });
    // console.log(htmlReport);

  } catch (error: any) {
    console.error('Error during dependency cruising:', error.message);
    process.exit(1);
  }
}

analyzeDependencies();

view raw JSON →