### Example Output Source: https://github.com/sverweij/dependency-cruiser/blob/main/test/extract/__mocks__/ts/README.md This is an example of the expected output when running the transpiled fixture. ```text 1.0.0-exportedonly, 8 === 8 : ``` -------------------------------- ### Command Line Invocation for Focus Example Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Example command to generate a dependency graph focusing on specific modules and their neighbors, outputting to an SVG file. ```bash depcruise -src c focus.config.json -T dot | dot -T svg > focus.svg ``` -------------------------------- ### Specify Base Directory Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Sets the starting directory for dependency analysis. There is no direct command-line equivalent. ```javascript module.exports = { options: { includeOnly: "^src/main", exclude: "/filesAndDirs/", }, }; ``` -------------------------------- ### Install dependency-cruiser Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/index.html Install dependency-cruiser as a development dependency in your project. ```bash npm i --save-dev dependency-cruiser ``` -------------------------------- ### Visualize all modules with highlight Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md Example command to generate a DOT graph showing all modules when using --highlight with watskeburt, suitable for smaller codebases. ```sh npx depcruise src types --include-only '^(src|types)' --highlight "$(watskeburt main)" --config --output-type dot | dot -T svg > with-highlight.svg ``` -------------------------------- ### Extend Recommended Configuration with Overrides Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/rules-reference.md This JavaScript example shows how to extend the 'recommended' configuration and override specific rules, such as changing the severity of 'no-deprecated-core' to 'warn'. ```javascript module.exports = { extends: "dependency-cruiser/configs/recommended", forbidden: [ { // because we still use a deprecated core module, still let // the no-deprecated-core rule from recommended fire, // but at least temporarily don't let it break our build // by setting the severity to "warn" here name: "no-deprecated-core", severity: "warn", // no need to specify the from and to, because they're already // defined in 'recommended' }, ], }; ``` -------------------------------- ### Install Dependency Cruiser Source: https://github.com/sverweij/dependency-cruiser/blob/main/README.md Install dependency-cruiser as a development dependency using npm, yarn, or pnpm. ```shell npm install --save-dev dependency-cruiser # or yarn add -D dependency-cruiser pnpm add -D dependency-cruiser ``` -------------------------------- ### Command line invocation for focus depth Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Example command to run dependency-cruiser with a focus depth configuration and generate a dot graph. ```sh depcruise src -c focus-depth-2.config.json -T dot | dot -T svg > focus-depth-2.svg ``` -------------------------------- ### Command line invocation for snazzy focus theme Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Example command to run dependency-cruiser with a focus theme configuration and generate a dot graph. ```sh depcruise src -c snazzy-focus.config.json -T dot | dot -T svg > snazzy-focus.svg ``` -------------------------------- ### Typical Metrics Reporter Output Example Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md This is a sample output from the 'metrics' reporter, showcasing the tabular format of stability metrics for modules and folders. ```text type name N Ca Ce I (%) size #tls ------- ----------------------------------------------- s------ ------ ------ ------ ----------- ------ folder src he he 100 % 36.125 99 folder src/cache 6 0 6 100 % 25.367 54 module src/cache/cache.mjs 1 0 5 100 % 5.817 12 module src/cache/content-strategy.mjs 1 1 2 67 % 3.948 7 module src/cache/find-content-changes.mjs 1 1 3 75 % 3.663 6 module src/cache/helpers.mjs 1 3 1 25 % 3.612 16 module src/cache/metadata-strategy.mjs 1 1 2 67 % 3.720 5 module src/cache/options-compatible.mjs 1 1 0 0 % 4.607 8 folder src/extract 2 1 1 50 % 4.985 20 folder src/extract/transpile 2 1 1 50 % 4.985 20 module src/extract/transpile/meta.mjs 1 1 2 67 % 3.519 10 module src/extract/transpile/try-import-available.mjs 1 1 0 0 % 1.466 10 folder src/graph-utl 1 1 0 0 % 382 3 module src/graph-utl/match-facade.mjs 1 1 0 0 % 382 3 module src/meta.cjs 1 1 0 0 % 467 1 folder src/utl 3 4 0 0 % 4.924 21 module src/utl/bus.mjs 1 3 0 0 % 766 10 module src/utl/find-all-files.mjs 1 1 1 50 % 3.040 9 module src/utl/path-to-posix.mjs 1 1 0 0 % 1.118 2 ``` -------------------------------- ### NDJSON Performance Log Entry Example Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md An example of a single ndjson log entry, detailing performance metrics for a specific processing step. This format is subject to change. ```json {"runStartTime":"2025-12-24T19:25:50.037Z","runId":213435185128416,"message":"startup: nodejs loading","time":297855,"elapsedTime":297855,"user":366111,"elapsedUser":366111,"system":48490,"elapsedSystem":48490,"rss":196329472,"heapUsed":78937168,"heapTotal":97124352,"external":11581186} ``` ```json {"runStartTime":"2025-12-24T19:25:50.037Z","runId":213435185128416,"message":"startup: parse options","time":300133,"elapsedTime":2278,"user":368517,"elapsedUser":2406,"system":48671,"elapsedSystem":181,"rss":196706304,"heapUsed":79231160,"heapTotal":97124352,"external":11581226} ``` ```json {"runStartTime":"2025-12-24T19:25:50.037Z","runId":213435185128416,"message":"startup: import analytical modules","time":315104,"elapsedTime":14971,"user":409243,"elapsedUser":40726,"system":52464,"elapsedSystem":3793,"rss":205144064,"heapUsed":57310320,"heapTotal":104366080,"external":2748843} ``` ```json {"runStartTime":"2025-12-24T19:25:50.037Z","runId":213435185128416,"message":"startup: parse rule set","time":326651,"elapsedTime":11547,"user":430393,"elapsedUser":21150,"system":52820,"elapsedSystem":356,"rss":205635584,"heapUsed":70138952,"heapTotal":104366080,"external":2757035} ``` ```json {"runStartTime":"2025-12-24T19:25:50.037Z","runId":213435185128416,"message":"startup: get resolve options","time":326741,"elapsedTime":90,"user":430467,"elapsedUser":74,"system":52836,"elapsedSystem":16,"rss":205635584,"heapUsed":70199840,"heapTotal":104366080,"external":2757035} ``` ```json {"runStartTime":"2025-12-24T19:25:50.037Z","runId":213435185128416,"message":"extract","time":523713,"elapsedTime":196971,"user":803754,"elapsedUser":373287,"system":77658,"elapsedSystem":24822,"rss":333938688,"heapUsed":121507992,"heapTotal":227934208,"external":2688354} ``` ```json {"runStartTime":"2025-12-24T19:25:50.037Z","runId":213435185128416,"message":"analyze","time":548901,"elapsedTime":25189,"user":843483,"elapsedUser":39729,"system":78831,"elapsedSystem":1173,"rss":336887808,"heapUsed":96978728,"heapTotal":230031360,"external":2688354} ``` ```json {"runStartTime":"2025-12-24T19:25:50.037Z","runId":213435185128416,"message":"report","time":551008,"elapsedTime":2107,"user":847523,"elapsedUser":4040,"system":78948,"elapsedSystem":117,"rss":336904192,"heapUsed":99378056,"heapTotal":230031360,"external":2688354} ``` -------------------------------- ### Compose Rule Sets with JavaScript Configuration Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/rules-reference.md Demonstrates how to use a JavaScript module to define configurations, allowing for composition of rule sets and dynamic rule definitions. This example imports and combines rules from separate JSON files. ```javascript const subNotAllowed = require("rules/sub-not-allowed.json"); const noInterComponents = require("rules/sub-no-inter-components.json"); module.exports = { forbidden: [subNotAllowed, noInterComponents], options: { tsConfig: { fileName: "./tsconfig.json", }, }, }; ``` -------------------------------- ### Sample TeamCity Reporter Output Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md Example output when dependency-cruiser is run with the 'teamcity' reporter, showing inspection types and violation messages. ```text ##teamcity[inspectionType id='not-to-dev-dep' name='not-to-dev-dep' description='Don|'t allow dependencies from src/app/lib to a development only package' category='dependency-cruiser' flowId='8970869134' timestamp='2019-06-02T10:37:56.812'] ##teamcity[inspectionType id='no-orphans' name='no-orphans' description='Modules without any incoming or outgoing dependencies are might indicate unused code.' category='dependency-cruiser' flowId='8970869134' timestamp='2019-06-02T10:37:56.812'] ##teamcity[inspectionType id='not-to-unresolvable' name='not-to-unresolvable' description='' category='dependency-cruiser' flowId='8970869134' timestamp='2019-06-02T10:37:56.812'] ##teamcity[inspection typeId='not-to-dev-dep' message='src/asneeze.js -> node_modules/eslint/lib/api.js' file='src/asneeze.js' SEVERITY='ERROR' flowId='8970869134' timestamp='2019-06-02T10:37:56.812'] ##teamcity[inspection typeId='not-to-unresolvable' message='src/index.js -> ./medontexist.json' file='src/index.js' SEVERITY='ERROR' flowId='8970869134' timestamp='2019-06-02T10:37:56.812'] ##teamcity[inspection typeId='not-to-dev-dep' message='src/index.js -> node_modules/dependency-cruiser/src/main/index.js' file='src/index.js' SEVERITY='ERROR' flowId='8970869134' timestamp='2019-06-02T10:37:56.812'] ##teamcity[inspection typeId='not-to-dev-dep' message='src/index.js -> node_modules/eslint/lib/api.js' file='src/index.js' SEVERITY='ERROR' flowId='8970869134' timestamp='2019-06-02T10:37:56.812'] ##teamcity[inspection typeId='no-orphans' message='src/orphan.js -> src/orphan.js' file='src/orphan.js' SEVERITY='ERROR' flowId='8970869134' timestamp='2019-06-02T10:37:56.812'] ``` -------------------------------- ### Sample Mermaid Graph Output Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md An example of the Mermaid graph format generated by the mermaid reporter, illustrating the structure of dependencies. ```mermaid flowchart LR subgraph src["src"] subgraph src_main["main"] subgraph src_main_rule_set["rule-set"] src_main_rule_set_normalize_js["normalize.js"] end src_main_index_js["index.js"] subgraph src_main_utl["utl"] src_main_utl_normalize_re_properties_js["normalize-re-properties.js"] end end end subgraph test["test"] subgraph test_enrich["enrich"] subgraph test_enrich_derive["derive"] subgraph test_enrich_derive_reachable["reachable"] test_enrich_derive_reachable_index_spec_mjs["index.spec.mjs"] end end end subgraph test_main["main"] subgraph test_main_rule_set["rule-set"] test_main_rule_set_normalize_spec_mjs["normalize.spec.mjs"] end end subgraph test_validate["validate"] test_validate_parse_ruleset_utl_mjs["parse-ruleset.utl.mjs"] end end subgraph node_modules["node_modules"] subgraph node_modules_lodash["lodash"] node_modules_lodash_has_js["has.js"] node_modules_lodash_cloneDeep_js["cloneDeep.js"] end end src_main_rule_set_normalize_js-->src_main_utl_normalize_re_properties_js src_main_rule_set_normalize_js-->node_modules_lodash_cloneDeep_js src_main_rule_set_normalize_js-->node_modules_lodash_has_js src_main_index_js-->src_main_rule_set_normalize_js test_enrich_derive_reachable_index_spec_mjs-->src_main_rule_set_normalize_js test_main_rule_set_normalize_spec_mjs-->src_main_rule_set_normalize_js test_validate_parse_ruleset_utl_mjs-->src_main_rule_set_normalize_js style src_main_rule_set_normalize_js fill:lime,color:black ``` -------------------------------- ### Sample Azure DevOps Reporter Output Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md Example output when dependency-cruiser is run with the 'azure-devops' reporter, showing errors, warnings, and a summary of the cruise. ```text ##vso[task.logissue type=error;sourcepath=src/asneeze.js;code=not-to-dev-dep;]src/asneeze.js -> node_modules/eslint/lib/api.js ##vso[task.logissue type=error;sourcepath=src/index.js;code=not-to-unresolvable;]src/index.js -> ./medontexist.json ##vso[task.logissue type=error;sourcepath=src/index.js;code=not-to-dev-dep;]src/index.js -> node_modules/eslint/lib/api.js ##vso[task.logissue type=warning;sourcepath=src/orphan.js;code=no-orphans;]src/orphan.js ##vso[task.complete result=Failed;]4 dependency violations (3 error, 1 warning/ informational). 8 modules, 7 dependencies cruised ``` -------------------------------- ### Dependency Object Example Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/nav-onetree.html Represents a resolved dependency with its properties like type, module, and resolution status. ```json { "resolved": "package.json", "coreModule": false, "followable": false, "couldNotResolve": false, "dependencyTypes": [ "local" ], "module": "../../../package.json", "moduleSystem": "cjs", "matchesDoNotFollow": false, "circular": false, "valid": true } ``` ```json { "resolved": "node_modules/semver-try-require/src/index.js", "coreModule": false, "followable": false, "couldNotResolve": false, "dependencyTypes": [ "npm" ], "license": "MIT", "module": "semver-try-require", "moduleSystem": "cjs", "matchesDoNotFollow": true, "circular": false, "valid": true } ``` ```json { "resolved": "fs", "coreModule": true, "followable": false, "couldNotResolve": false, "dependencyTypes": [ "core" ], "module": "fs", "moduleSystem": "cjs", "matchesDoNotFollow": false, "circular": false, "valid": true } ``` -------------------------------- ### Google Analytics Setup Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/index.html This JavaScript code initializes Google Analytics tracking for the page. It requires the 'ga' function to be available globally. ```javascript (function (i, s, o, g, r, a, m) { i["GoogleAnalyticsObject"] = r; (i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments); }), (i[r].l = 1 * new Date()); (a = s.createElement(o)), (m = s.getElementsByTagName(o)[0]); a.async = 1; a.src = g; m.parentNode.insertBefore(a, m); })( window, document, "script", "https://www.google-analytics.com/analytics.js", "ga" ); ga("create", "UA-92990402-1", "auto"); ga("send", "pageview"); ``` -------------------------------- ### Initialize and Display Project Modules Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/nav-onetree.html Sorts the modules by source name, filters out modules starting with 'node_modules', and then creates a file node for each remaining module. Finally, it resets the file node classes. ```javascript lDependencies.modules .sort(compareModule) .filter((pModule) => !pModule.source.startsWith("node_modules")) .forEach((pModule) => { createFileNode(pModule.source); }); resetFileNodes(); ``` -------------------------------- ### Cruising Multiple Files and Directories Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md Example of how to specify multiple files and directories to be cruised by dependency-cruiser. This command will cruise all files within the 'src', 'test', and 'lib' directories, plus 'index.ts' in the root. ```sh depcruise --output-type dot src test lib index.ts ``` -------------------------------- ### Cruise Dependencies with Options Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/api.md Pass cruise options to refine the analysis, such as specifying which files to include. This example uses `includeOnly` to limit the cruise to the 'src' directory. ```typescript import { cruise, IReporterOutput, ICruiseOptions } from "dependency-cruiser"; const ARRAY_OF_FILES_AND_DIRS_TO_CRUISE: string[] = ["src"]; const cruiseOptions: ICruiseOptions = { includeOnly: "src", }; try { const cruiseResult: IReporterOutput = await cruise( ARRAY_OF_FILES_AND_DIRS_TO_CRUISE, cruiseOptions, ); console.dir(cruiseResult.output, { depth: 10 }); } catch (pError) { console.error(pError); } ``` -------------------------------- ### Generate Flat Dependency Graph for State Machine Cat Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/real-world-samples.md Clones the state-machine-cat repository, installs dependencies, and then runs dependency-cruiser with a specific configuration to generate a 'flat' output type. This output is then piped through Graphviz and a wrapper to create an interactive HTML graph, saving both the SVG and HTML files. ```bash git clone git@github.com:sverweij/state-machine-cat.git cd state-machine-cat npm install npx depcruise src bin/smcat --progress \ --config config/dependency-cruiser-graph.js \ --output-type flat \ | dot -Tsvg \ | tee docs/dependency-cruiser-graph-flat-dot.svg \ | npx depcruise-wrap-stream-in-html \ > docs/dependency-cruiser-graph-flat-dot.html ``` -------------------------------- ### Filter Dependencies for Graph Generation Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/faq.md Apply filters like --include-only and --exclude on the command line to reduce the number of modules and dependencies shown in the dot output. This example focuses on 'src' and excludes test and mock files. ```sh depcruise src --include-only "^src/" --exclude "mocks\.ts$|\.spec\.ts$" --output-type dot | dot -T svg > dependency-graph.svg ``` -------------------------------- ### Prefixing Links in Dot Output Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md Use the --prefix option to add a string to the beginning of links in the dot output, useful for creating links to online repositories. This example generates an SVG dependency graph with links to GitHub. ```sh dependency-cruise --prefix "https://github.com/you/yourrepo/tree/master/" -T dot src | dot -T svg > dependency-graph-with-links-to-gh.svg ``` -------------------------------- ### Dependency Cruiser Data Model Example Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/nav.html This JavaScript object represents the data model for Dependency Cruiser, detailing module dependencies, rules, and summary statistics. It includes information about resolved modules, core modules, npm packages, and rule violations. ```javascript var lModel = [ [ { name: "src/main/index.js", level: 0, valid: true, }, ], ]; var lDependencies = { modules: [ { source: "src/cli/index.js", dependencies: [ { resolved: "./defaults.json", coreModule: false, followable: true, couldNotResolve: false, dependencyTypes: ["local"], module: "./defaults.json", moduleSystem: "cjs", matchesDoNotFollow: false, circular: false, valid: true, }, { resolved: "fs", coreModule: true, followable: false, couldNotResolve: false, dependencyTypes: ["core"], module: "fs", moduleSystem: "cjs", matchesDoNotFollow: false, circular: false, valid: true, }, { resolved: "node_modules/lodash/lodash.js", coreModule: false, followable: false, couldNotResolve: false, dependencyTypes: ["npm"], license: "MIT", module: "lodash", moduleSystem: "cjs", matchesDoNotFollow: true, circular: false, valid: false, rules: [ { severity: "info", name: "prefer-no-lodash", }, ], }, ], valid: true, }, { source: "src/cli/validateFileExistence.js", dependencies: [ { resolved: "fs", coreModule: true, followable: false, couldNotResolve: false, dependencyTypes: ["core"], module: "fs", moduleSystem: "cjs", matchesDoNotFollow: false, circular: false, valid: true, }, ], valid: true, }, ], summary: { violations: [ { from: "src/cli/index.js", to: "node_modules/lodash/lodash.js", rule: { severity: "info", name: "prefer-no-lodash", }, }, { from: "src/cli/normalizeOptions.js", to: "node_modules/lodash/lodash.js", rule: { severity: "info", name: "prefer-no-lodash", }, }, { from: "src/extract/extract.js", to: "node_modules/lodash/lodash.js", rule: { severity: "info", name: "prefer-no-lodash", }, }, { from: "src/extract/index.js", to: "node_modules/lodash/lodash.js", rule: { severity: "info", name: "prefer-no-lodash", }, }, ], error: 0, warn: 0, info: 4, totalCruised: 79, optionsUsed: { rulesFile: ".dependency-cruiser-custom.json", outputTo: "-", doNotFollow: "^node_modules", exclude: "fixtures", moduleSystems: ["amd", "cjs", "es6"], outputType: "json", prefix: "https://github.com/sverweij/dependency-cruiser/blob/main/", tsPreCompilationDeps: false, preserveSymlinks: false, }, }, }; ``` -------------------------------- ### Display Dependency Cruiser Environment Info Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md Use the --info flag to see supported node versions, found versions, OS details, and available transpiler/extension support. This command ignores any other arguments. ```bash depcruise --info ``` -------------------------------- ### Type declaration with import Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/rules-reference.md Example of using an import statement within a type declaration. ```typescript const lAThing: import('./things').IThing = {} ``` -------------------------------- ### Triple-Slash Directives Source: https://github.com/sverweij/dependency-cruiser/blob/main/test/extract/all-shapes-of-import-export.md Includes examples of triple-slash directives used for referencing files or types in TypeScript. ```typescript /// /// ``` -------------------------------- ### Event Listeners for Hints and Help Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/assets/berry-high-level-dependencies.html Sets up event listeners for closing hints and toggling help information. ```javascript document.getElementById("close-hints").addEventListener("click", hints.hide); ``` ```javascript document.getElementById("button_help").addEventListener("click", hints.toggle); ``` -------------------------------- ### Exporting a Variable in CoffeeScript Source: https://github.com/sverweij/dependency-cruiser/blob/main/test/extract/__mocks__/coffee/sub/willBeReExported.coffee.md This snippet shows a basic CoffeeScript export statement. It's part of a literate programming example. ```coffeescript export exportedonly = "exportedonly" ``` -------------------------------- ### Initialize Dependency Cruiser Configuration Source: https://github.com/sverweij/dependency-cruiser/blob/main/README.md Generate a .dependency-cruiser.js configuration file tailored to your project by running the init command. ```shell npx depcruise --init ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md The basic structure for using the dependency-cruiser CLI. Pass options and then the files or directories to cruise. ```sh depcruise [options] ``` -------------------------------- ### Run Dependency Cruiser Source: https://github.com/sverweij/dependency-cruiser/blob/main/README.md Execute dependency-cruiser on the 'src' directory to report dependency violations. ```sh npx depcruise src ``` -------------------------------- ### Show Dependents and Select File Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/nav-onetree.html Resets file node classes, finds the module by filename, selects the corresponding node by setting its class, and then creates file nodes for all its dependencies. Logs an empty line to the console. ```javascript function showDependents(pFileName) { resetFileNodes(); var lNode = lDependencies.modules.find( (pModule) => pModule.source === pFileName ); document .getElementById(pFileName) .setAttribute("class", "js-file-node klikstra selected"); lNode.dependencies .map((pDependent) => pDependent.resolved) .forEach((pDependentFileName) => { createFileNode(pDependentFileName); }); console.log(); } ``` -------------------------------- ### Excluding Multiple Directories Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Exclude modules from directories starting with 'coverage', 'test', or 'node_modules' using a combined regular expression for the path. ```json "options": { "exclude": { "path": "^(coverage|test|node_modules)" } } ``` -------------------------------- ### Combine Prefix and Suffix for Report Links Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Demonstrates how `prefix` and `suffix` options work together to construct full URLs for report links, transforming module paths into complete URLs. ```javascript prefix: "coverage/", suffix: ".gcov.html" ``` -------------------------------- ### Get Title Text from SVG Element Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/dependency-cruiser-dependency-graph.html Extracts and trims the text content from the element within a given SVG element. ```javascript function getTitleText(pGElement) { /** @type {SVGTitleElement} */ var title = pGElement && pGElement.querySelector("title"); /** @type {string} */ var titleText = title && title.textContent; if (titleText) { titleText = titleText.trim(); } return titleText; } ``` -------------------------------- ### Get Title Text from SVG Element Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/assets/react-high-level-dependencies.html Extracts the text content from the SVG <title> element associated with a given SVG element. ```javascript /** * @param {SVGGElement} pGElement * @return {string?} */ function getTitleText(pGElement) { /** @type {SVGTitleElement} */ var title = pGElement & ``` -------------------------------- ### Generating JSON Report and Formatting Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Demonstrates a two-step process for generating dependency reports: first, create a JSON output using depcruise, then format it using depcruise-fmt. ```bash # depcruise reads all specified modules from disk and parses them to infer # dependencies. For big repos this can take a while depcruise src bin test -T json -c > results.json # depcruise-fmt reads the result of a cruise and emits a report # on it, so it doesn't need to do the expensive disk access & parse # step. These three formatting steps together will take a lot less ``` -------------------------------- ### Create and Highlight File Node Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/nav-onetree.html Creates a new 'div' element for a file if it doesn't exist, sets its class to 'js-file-node klikstra', assigns an ID, and adds a click event listener to show dependents. If the file exists, it highlights it. ```javascript function createFileNode(pFileName) { var lDiv = document.getElementById(pFileName); if (!lDiv) { lDiv = document.createElement("div"); lDiv.setAttribute("class", "js-file-node klikstra"); lDiv.setAttribute("ID", pFileName); lDiv.textContent = pFileName; lDiv.addEventListener("click", (pEvent) => showDependents(pEvent.target.innerText) ); document.body.appendChild(lDiv); } lDiv.setAttribute("class", "js-file-node klikstra highlighted"); } ``` -------------------------------- ### Basic Dependency Cruise with Configuration Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md Use the 'err' output type for build scripts when combined with a configuration file. This is the default reporter. ```sh dependency-cruise --config my-depcruise-rules.json src ``` -------------------------------- ### Get Page Title Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/assets/react-high-level-dependencies.html Extracts and trims the text content of the page's title element. Returns null if the title element is not found. ```javascript function getPageTitle(pGElement) { var title = pGElement.querySelector("title"); /** @type {string} */ var titleText = title && title.textContent; if (titleText) { titleText = titleText.trim(); } return titleText; } ``` -------------------------------- ### Mode Management Utility Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/dependency-cruiser-dependency-graph.html A utility object to manage the interaction mode (HOVER or SELECT). Provides methods to set and get the current mode. ```javascript function Mode() { var HOVER = 1; var SELECT = 2; function setToHover() { this._mode = HOVER; } function setToSelect() { this._mode = SELECT; } /** * @returns {number} */ function get() { return this._mode || HOVER; } return { HOVER: HOVER, SELECT: SELECT, setHover: setToHover, setSelect: setToSelect, get: get }; } ``` -------------------------------- ### Enable Code Completion for Configuration Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/faq.md Configure your editor for code completion in `.dependency-cruiser.js` files by exporting the configuration with a type hint. ```javascript /** @type {import('dependency-cruiser').IConfiguration} */ export default { // ... your rules & options }; ``` -------------------------------- ### Dependency Cruiser CLI Usage Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md Displays the help message for the dependency-cruiser CLI, outlining available commands and options. ```bash Usage: depcruise-fmt [options] <dependency-cruiser-json> Format dependency-cruiser output json. Details: https://github.com/sverweij/dependency-cruiser Options: -f, --output-to <file> file to write output to; - for stdout (default: "-") -T, --output-type <type> output type; e.g. err, err-html, dot, ddot, archi, flat, baseline or json (default: "err") -I, --include-only <regex> only include modules matching the regex -F, --focus <regex> only include modules matching the regex + their direct neighbours -x, --exclude <regex> exclude all modules matching the regex -S, --collapse <regex> collapse the modules to the regex pattern E.g. ^packages/[^/]+/ collapses to modules/ folders directly under your packages folder. Or pass a single digit (e.g. 2) to collapse to a folder depth. -e, --exit-code exit with a non-zero exit code when the input json contains error level dependency violations. Works for err, err-long and teamcity output types -V, --version output the version number -h, --help display help for command ``` -------------------------------- ### Limiting Cruise Depth to 1 Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Limit the dependency analysis to a maximum depth of 1, starting from the specified root modules. Useful for high-level overviews. ```javascript ... "maxDepth": 1 ... ``` -------------------------------- ### Get SVG Element by Title Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/dependency-cruiser-dependency-graph.html Retrieves SVG elements that have a specific title text. Returns an array of elements or an empty array if none are found. ```javascript function get(pTitleText) { return (pTitleText && elementMap[pTitleText]) || []; } ``` -------------------------------- ### Finding Specific Module Dependencies with depcruise-fmt Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md Illustrates how to use depcruise-fmt with the --focus option to find and display dependencies related to a specific module, like 'spelunk-me.ts', in a text format. ```sh depcruise-fmt -T text --focus "^src/main/spelunk-me\.ts$" cruise_result.json ``` -------------------------------- ### Get Title Text from SVG Element Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/assets/berry-high-level-dependencies.html Extracts and trims the text content from an SVG 'title' element within a given SVG group element. ```javascript function getTitleText(pGElement) { var title = pGElement && pGElement.querySelector("title"); var titleText = title && title.textContent; if (titleText) { titleText = titleText.trim(); } return titleText; } ``` -------------------------------- ### Configure 'conditionNames' for package.json exports Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Define the conditions to check within the 'exports' field of package.json. For example, use `['imports']` for ES modules or `['require']` for CommonJS. ```javascript enhancedResolveOptions: { conditionNames: ['import', 'require', 'node', 'default']; } ``` -------------------------------- ### Custom Archi Reporter Theme for Collapsed Modules Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Defines a custom theme for the archi reporter to change the appearance of collapsed modules, for example, to a 'tab' shape. ```javascript // ... reporterOptions: { archi: { // ... theme: { modules: [ { criteria: { collapsed: true }, attributes: { shape: "tab" } } ] } } // ... ``` -------------------------------- ### Configure Webpack Configuration with Parameters Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Provide environment and arguments to a webpack configuration function when specifying it for dependency-cruiser. This is useful for configurations that depend on these parameters. ```json "options": { "webpackConfig": { "fileName": "webpack.config.js", "env": { "production": true }, "arguments": { "mode": "production" } } } ``` -------------------------------- ### Rule: Detect unresolvable dependencies Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/rules-reference.md Configure this rule in the 'forbidden' section to get an error for each dependency that dependency-cruiser cannot resolve. This typically indicates modules that are not present on disk. ```json { "name": "not-to-unresolvable", "severity": "error", "from": {}, "to": { "couldNotResolve": true } } ``` -------------------------------- ### Using an array of regular expressions for 'to.pathNot' Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/rules-reference.md Improve legibility of complex regular expressions by expressing them as an array. This example shows how to exclude multiple patterns from the 'to' path. ```javascript { from: { path: "(^src/report/)" }, to: { pathNot: "$1|^node_modules|^(path|package.json)$|^src/utl" } } ``` ```javascript { from: { path: "(^src/report/)" }, to: { pathNot: [ "$1", "^node_modules", "^(path|package.json)$", "^src/utl" ] } } ``` -------------------------------- ### Configure Exotic Require Strings Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Specify alternative function names or paths used for module loading when direct 'require' is not feasible. Useful for AMD or custom module loaders. ```json "options": { "exoticRequireStrings": ["want", "tryRequire", "window.require"] } ``` -------------------------------- ### Focus on Modules and Their Neighbors with focus Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Configure dependency-cruiser to show modules matching a pattern and their neighbors. This option is often used with includeOnly or doNotFollow to speed up analysis. ```json { "options": { "includeOnly": "^src/", "focus": "^src/main/" } } ``` -------------------------------- ### Get Title Text from Element Source: https://github.com/sverweij/dependency-cruiser/blob/main/types/overview.html Extracts and trims the text content from the 'title' element within a given SVG element. Returns null if no title element is found. ```typescript /** * @param {SVGGElement} pGElement * @return {string?} */ function getTitleText(pGElement) { /* @type {SVGTitleElement} */ var title = pGElement && pGElement.querySelector('title'); /* @type {string} */ var titleText = title && title.textContent; if (titleText) { titleText = titleText.trim(); } return titleText; } ``` -------------------------------- ### Render Orthogonal Edges in Dot Output Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/faq.md Use this command to generate a dependency graph with orthogonal edges instead of splines for improved legibility. Ensure GraphViz is installed and accessible. ```sh depcruise src --config .dependency-cruiser-graph.js --output-type dot | dot -Gsplines=ortho -T svg > dependency-graph-with-orthogonal-edges.svg ``` -------------------------------- ### Add New Transpiler Support Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/faq.md Steps to add support for a new alt-JS language by updating `package.json`, creating a wrapper script, and configuring extension mappings. ```javascript // In src/transpile/yourLanguageWrap.js // ... invoke the transpiler transforming your language into JavaScript // In src/extract/transpile/index.js // ... add an entry for './yourLanguageWrap' to the EXTENSION2WRAPPER map ``` -------------------------------- ### JSX Parsing Caveat Example Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/faq.md This JSX code demonstrates a rare case where the default parser might misinterpret 'import' or 'export' within fragments as actual import/export statements. ```jsx import React from "react"; export class ReplicateIssueComponent extends React.Component { renderSomethingElse = () => { return ( <>The word import here results is picked up as an import statement.</> ); }; render = () => ( <> {this.renderSomethingElse()} Here import is confused with an import statement as well. </> ); } ``` -------------------------------- ### Filtering Dependencies with depcruise-fmt Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md Shows how to use depcruise-fmt with filtering options like --focus and --include-only to generate specific DOT graph visualizations for parts of the project, such as the 'main' or 'juggle' directories, or modules matching a specific pattern. ```sh depcruise-fmt -T dot --focus "^src/main" cruise_result.json | dot -T svg > main.svg depcruise-fmt -T dot --focus "^src/juggle" cruise_result.json | dot -T svg > juggle.svg depcruise-fmt -T dot --include-only "^src/the-law" cruise_result.json | dot -T svg > the-law.svg ``` -------------------------------- ### Get File Node Level Source: https://github.com/sverweij/dependency-cruiser/blob/main/docs/nav.html This JavaScript function finds the level of a given file name within the `lModel` array. It returns the index of the level if found, otherwise -1. ```javascript function getLevel(pFileName) { return lModel.findIndex((pLevel) => pLevel.some((pNode) => pNode.name === pFileName) ); } ``` -------------------------------- ### Specify Parser Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Set the `parser` option to 'tsc' to use Microsoft's TypeScript parser, which can also handle JavaScript. Ensure 'typescript' is installed. The 'acorn' parser is the default for JavaScript. ```javascript { // ... options: { parser: "tsc"; } } ``` -------------------------------- ### Use tsconfig.json on the Command Line Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md Instruct dependency-cruiser to use the tsconfig.json in the current directory for analyzing TypeScript sources. ```sh depcruise --ts-config --validate -- src ``` -------------------------------- ### Detect Non-Package JSON Dependencies with `dependencyTypes` Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/rules-reference.md Use `dependencyTypes` to identify dependencies that were installed but not saved to `package.json`, or other unknown dependency types. This prevents runtime issues caused by missing dependencies. ```json { "name": "no-non-package-json", "severity": "error", "comment": "because an npm i --production will otherwise deliver an unreliably running package", "from": { "pathNot": "^(node_modules)" }, "to": { "dependencyTypes": ["unknown", "undetermined", "npm-no-pkg", "npm-unknown"] } } ``` -------------------------------- ### Enforce Type-Only Imports with `dependencyTypesNot` Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/rules-reference.md Use `dependencyTypesNot` in conjunction with path rules to ensure that type-only imports are used appropriately, for example, when importing from type declaration files or specific modules. ```json { "name": "only-type-only", "comment": "use explicit 'type' imports to import from type declaration modules", "severity": "error", "from": {}, "to": { "path": ["types\\.ts$", "\\.d\\.ts$"], "dependencyTypesNot": ["type-only"] } } ``` -------------------------------- ### Generate Interactive Dependency Graph (DOT) Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/real-world-samples.md Generates a dependency graph in DOT format, processes it with Graphviz to create an SVG, and then wraps it in HTML for interactive viewing in a browser. This is useful for visualizing project dependencies. ```bash node ./bin/dependency-cruise.js bin src --prefix vscode://file/$(pwd)/ --config --output-type dot | \ # format the output with dot dot -T svg | \ # process the svg into an interactive html graph node ./bin/wrap-stream-in-html.js | \ # The browser command opens the graph-in-html just produced in your # default browser browser ``` -------------------------------- ### Anonymize Path Element Examples Source: https://github.com/sverweij/dependency-cruiser/blob/main/src/report/anon/anonymize-path-element.md Demonstrates how anonymizePathElement transforms file paths. It replaces parts of the path with words from a whitelist, preserves extensions, and handles paths with and without whitelisted components. ```text superSecureThing.ts => abandon.ts ``` ```text superSecureThing.spec.ts => abandon.spec.ts ``` ```text src/index.ts => src/index.ts // 'src' and 'index' are in the whitelist ``` ```text lib/somethingElse.service.js => lib/ability.service.js ``` -------------------------------- ### Err-Long Output Type for Detailed Violations Source: https://github.com/sverweij/dependency-cruiser/blob/main/doc/cli.md Use 'err-long' output type to include the comment associated with each violated rule, providing context and potential fixes. Useful for lint-staged setups. ```sh dependency-cruise --output-type err-long --config my-depcruise-rules.json src ```