npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@thepassle/module-graph

v0.11.0

Published

Creates a module graph based on a given entrypoint.

Downloads

363

Readme

Module graph

Creates a module graph based on a given entrypoint. Supports ESM, monorepos, import attributes, typescript (via a plugin) and is extensible via plugins. Builds on top of es-module-lexer for scanning a module's imports, and oxc-resolver for module resolution.

Installation

npm i @thepassle/module-graph

Usage

import { createModuleGraph } from '@thepassle/module-graph';

const moduleGraph = await createModuleGraph('./index.js');

/**
 * Multiple entrypoints
 */
const moduleGraph = await createModuleGraph(['./foo.js', './bar.js']);

/**
 * Configuration options
 * Supports all `oxc-resolver`'s `NapiResolveOptions` options.
 * https://github.com/oxc-project/oxc-resolver?tab=readme-ov-file#oxc-resolver
 */
const moduleGraph = await createModuleGraph('./index.js', {
  basePath: process.cwd(),
  exportConditions: ['browser', 'import'],
  /** Handle external modules */
  external: {
    /** Ignore all external modules imported via a bare module specifier */
    ignore: true,
    /** Only include external modules from these packages */
    include: ['bar'],
    /** Exclude bare module specifiers */
    exclude: ['foo', '@foo/bar'],
  },
  /** Picomatch glob pattern or callback */
  exclude: [
    '**/ignore.js',
    '**/foo/*.js',
    (importee) => importee.includes('foo')
  ],
  /** Ignores dynamic imports */
  ignoreDynamicImport: true,
  plugins: [myPlugin]
});

createModuleGraph analyzes only ESM-style imports, not require. However, if a CommonJS file is found and uses a dynamic import, it will include the dynamic import in the graph and any other imports that leads to.

Typescript

If you want to analyze typescript source code, you can use the typescript plugin:

import { createModuleGraph } from '@thepassle/module-graph';
import { typescript } from '@thepassle/module-graph/plugins/typescript.js';

const moduleGraph = await createModuleGraph('./index.ts', {
  plugins: [typescript()]
});

The default is set to ESM, which means it expects .js file extensions in your code. However, you can also provide your tsconfig.json options to the typescript plugin, to resolve extensionless typescript imports, e.g.: import { Foo } from './foo';:

import { createModuleGraph } from '@thepassle/module-graph';
import { typescript } from '@thepassle/module-graph/plugins/typescript.js';

const moduleGraph = await createModuleGraph('./index.ts', {
  plugins: [typescript({
    compilerOptions: {
      moduleResolution: "node",
    }
  })]
});

CLI

# List all modules in the graph
npx @thepassle/module-graph index.js
npx @thepassle/module-graph foo.js,bar.js

# Find import chains for a given module
npx @thepassle/module-graph import-chain entrypoint.js module-to-find.js

# Find specific module
npx @thepassle/module-graph find entrypoint.js module-to-find.js

All CLI commands also allow the --ts option if your source code is in Typescript, and this can be combined with the --node flag if you're using extensionless imports in Typescript. E.g.:

npx @thepassle/module-graph find entrypoint.ts module-to-find.ts --ts --node

ModuleGraph

get

const moduleGraph = await createModuleGraph('./index.js');

const foo = moduleGraph.get('foo.js');
/** Or use picomatch pattern */
const bar = moduleGraph.get('**/bar.js');

/**
 * Or:
 */
const foo = moduleGraph.get((p) => p.endsWith('foo.js'));

getUniqueModules

const moduleGraph = await createModuleGraph('./index.js');

const uniqueModules = moduleGraph.getUniqueModules();

findImportChains

const moduleGraph = await createModuleGraph('./index.js');

const chains = moduleGraph.findImportChains('baz.js');

/**
 * Or:
 */
const chains = moduleGraph.findImportChains((p) => p.endsWith('baz.js'));

chains.forEach((c) => console.log(c.join(" -> ")));
// index.js -> bar.js -> baz.js

Plugins

You can also extend the default behavior by providing plugins. There are several default, opt-in plugins available:

  • Typescript analyze TS source code. Takes a compilerOptions object.
  • Imports outputs additional analysis of every modules imports on the Module object
  • Exports outputs additional analysis of every modules exports on the Module object
  • Barrel-file analyzes every module to see if it's a barrel file
  • Unused-exports finds unused exports in your module graph
import { typescript } from '@thepassle/module-graph/plugins/typescript.js';
import { imports } from '@thepassle/module-graph/plugins/imports.js';
import { exports } from '@thepassle/module-graph/plugins/exports.js';
import { barrelFile } from '@thepassle/module-graph/plugins/barrel-file.js';
import { unusedExports } from '@thepassle/module-graph/plugins/unused-exports.js';

const moduleGraph = await createModuleGraph('./index.js', {
  plugins: [
    typescript(),
    imports,
    exports,
    unusedExports,
    barrelFile({
      amountOfExportsToConsiderModuleAsBarrel: 3
    })
  ]
});

const module = moduleGraph.get('index.js');

module.imports; // Array of `Import`
module.exports; // Array of `Export`
module.isBarrelFile; // true
module.unusedExports; // Array of `Export`

See the documentation for more information on the Import and Export objects.

Creating plugins

Hooks

All plugin hooks can be async.

start

Runs once

Use for initializing logic of the plugin

const plugin = {
  name: 'my-plugin',
  start: ({entrypoints, basePath, exportConditions}) => {
    console.log('Plugin start');
  }
}

const moduleGraph = await createModuleGraph('./index.js', {
  plugins: [plugin]
});

handleImport

Runs for every import starting (but excluding) the entrypoints

Can be used to implement custom logic or rewrite a specifier

  • If false is returned, the import will be skipped entirely
  • If a string is returned, it will try to resolve that instead
const plugin = {
  name: 'my-plugin',
  handleImport: ({source, importer, importee}) => {
    if (importee.endsWith('?skip')) {
      return false;
    }
  }
}

const moduleGraph = await createModuleGraph('./index.js', {
  plugins: [plugin]
});

analyze

Runs for every module

Can be used to analyze the module (or its source), and add additional meta information to the Module object

You can mutate the module directly, no need to return it

const plugin = {
  name: 'my-plugin',
  analyze: (module) => {
    if (module.source.includes('process.env')) {
      module.usesProcessEnv = true;
    }
  }
}

const moduleGraph = await createModuleGraph('./index.js', {
  plugins: [plugin]
});

moduleGraph.get('module-containing-process-env.js').usesProcessEnv; // true

resolve

Runs for every import starting (but excluding) the entrypoint

Can be used to implement custom resolution logic. Gets passed the resolveOptions passed to createModuleGraph. If a plugin resolves the module and returns it from the resolve hook, consequent plugins will no longer be executed, because the module is already resolved.

  • If nothing is returned, the default resolution will be used
  • If a URL is returned, it will output that instead
const plugin = {
  name: 'my-plugin',
  resolve: ({ importee, importer, exportConditions, ...resolveOptions }) => {
    return customResolve(importee, importer, exportConditions);
  }
}

const moduleGraph = await createModuleGraph('./index.js', {
  plugins: [plugin]
});

end

Runs once

Use for cleanup logic of the plugin

const plugin = {
  name: 'my-plugin',
  end: (moduleGraph) => {
    console.log('Plugin end')
    moduleGraph.foo = 'bar';
  }
}

const moduleGraph = await createModuleGraph('./index.js', {
  plugins: [plugin]
});

moduleGraph.foo; // 'bar'

Example plugin

For example, if you want to create a graph visualization, you could create a digraph plugin like so:

import { exportToFile } from "@ts-graphviz/node";
import { createModuleGraph } from '@thepassle/module-graph';

const digraphPlugin = {
  name: 'digraph-plugin',
  end(moduleGraph) {
    let digraph = 'digraph {\n';
    for (const [parent, importees] of moduleGraph.graph) {
      digraph += `  "${parent}" -> ${[...importees].map(p => `"${p}"`).join(',')}\n`;
    }
    digraph += '}';

    moduleGraph.digraph = digraph;
  }
}

const moduleGraph = await createModuleGraph('./entrypoint.js', {
  plugins: [digraphPlugin]
});

await exportToFile(moduleGraph.digraph, {
  format: "png",
  output: "./example.png",
});