What is detective-cjs?
The detective-cjs package is a tool designed for analyzing JavaScript files to extract their CommonJS (require) dependencies. It parses the source code of a JavaScript file and identifies the modules that the file depends on by looking for 'require' statements. This can be particularly useful for tasks such as bundling, dependency analysis, and refactoring.
What are detective-cjs's main functionalities?
Extracting dependencies from a file
This feature allows you to pass JavaScript source code as a string to the detective function, which returns an array of strings representing the dependencies found in the source code. It's useful for identifying which modules a particular file is dependent on.
const detective = require('detective-cjs');
const src = `const foo = require('foo');
const bar = require('./bar.js');`;
const dependencies = detective(src);
console.log(dependencies); // ['foo', './bar.js']
Other packages similar to detective-cjs
detective
Detective is a more general version of detective-cjs, capable of handling various module systems including ES6 imports, AMD, and CommonJS. While detective-cjs focuses specifically on CommonJS (require) dependencies, detective provides a broader analysis toolset for different module types.
madge
Madge is a tool built on top of detective and other similar modules, designed for creating graphs of module dependencies and finding circular dependencies within a project. It supports ES6, AMD, and CommonJS. Compared to detective-cjs, Madge offers a higher-level analysis including visualization and more complex dependency analysis features.
precinct
Precinct is a tool that abstracts over detective, detective-amd, and detective-es6, among others, to provide a unified interface for extracting dependencies from files regardless of the module definition style. It's more versatile than detective-cjs as it can handle multiple module formats without needing to specify which detective to use.
detective-cjs
Get the dependencies of a CommonJS module by traversing its AST
npm install detective-cjs
But dude, substack already built this: node-detective. Yes, but I needed the capability to reuse an AST
and this was unlikely to be merged timely. I can also support jsx and other syntactic constructs faster.
Usage
const fs = require('fs');
const detective = require('detective-cjs');
const mySourceCode = fs.readFileSync('myfile.js', 'utf8');
const dependencies = detective(mySourceCode);
License
MIT