TypeScript Dependency Detective

14.1.1 · active · verified Sun Apr 19

detective-typescript is a utility library designed to extract the static dependencies from TypeScript module source code or its Abstract Syntax Tree (AST). It provides a programmatic API to analyze imports and exports, including support for various TypeScript features like type-only imports, dynamic imports, and JSX syntax. The current stable version is 14.1.1, with releases occurring somewhat regularly to support newer TypeScript versions and Node.js environments, and to address bug fixes and performance improvements. It differentiates itself by offering fine-grained control over dependency extraction through options like `skipTypeImports`, `mixedImports`, and `skipAsyncImports`, making it suitable for tools that need to build dependency graphs or perform static analysis on TypeScript projects. Its dependency extraction mechanism is robust, relying on AST parsing provided by `@typescript-eslint/typescript-estree`, and it is often used by build tools, bundlers, and linters for static code analysis.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates extracting static and dynamic dependencies from TypeScript code using various options.

import fs from 'node:fs';
import path from 'node:path';
import detective from 'detective-typescript';

// Example TypeScript code with various import types
const tsSourceCode = `
import { SomeType } from './types';
import { utilityFunction } from '@scope/utils';
import defaultExport from 'my-module';
import * as all from './all-exports';
const dynamicImport = import('./lazy-module');

interface MyInterface extends SomeType {}

export class MyClass {
  constructor() {
    utilityFunction();
    console.log(defaultExport);
  }
}
`;

// Create a dummy file to simulate reading from disk
const filePath = path.join(process.cwd(), 'temp-file.ts');
fs.writeFileSync(filePath, tsSourceCode, 'utf8');

try {
  const mySourceCode = fs.readFileSync(filePath, 'utf8');

  // Get all dependencies, including dynamic imports
  const dependencies = detective(mySourceCode, { skipAsyncImports: false });
  console.log('All dependencies:', dependencies);
  // Expected: [ './types', '@scope/utils', 'my-module', './all-exports', './lazy-module' ]

  // Get only static dependencies (excluding dynamic imports)
  const staticDependencies = detective(mySourceCode, { skipAsyncImports: true });
  console.log('Static dependencies:', staticDependencies);
  // Expected: [ './types', '@scope/utils', 'my-module', './all-exports' ]

  // Skip type-only imports (if 'SomeType' was a type-only import)
  const nonTypeDependencies = detective(mySourceCode, { skipTypeImports: true });
  console.log('Non-type dependencies:', nonTypeDependencies);

} catch (error) {
  console.error('Error processing file:', error);
} finally {
  fs.unlinkSync(filePath);
}

view raw JSON →