Skip to content

💡 Glob Pattern Import Support #1221

@rriski

Description

@rriski

Feature Request: Glob Pattern Import Support

Hello and thanks for this excellent tool! To make Knip even more effective for projects, I'd like to propose native support for dynamic glob imports.

The Idea

Extend Knip's import resolution to support the glob patterns used by webpack and Vite, as well as ES6-style glob imports.

Currently, these patterns result in unresolved import errors, leading to false positives for files that are used.

Patterns to Support

  1. ES6-style Glob Imports:
    Standard wildcard imports used with bundler plugins.

    // Import all feature modules from a directory
    import features from './features/**/*.feature.ts';
  2. Webpack require.context:
    A webpack-specific function for creating a dynamic context of modules.

    // Load all .js files from the './modules' directory
    const modules = require.context('./modules', true, /\.js$/);
  3. Vite import.meta.glob:
    Vite's built-in function for glob-based module importing.

    // Lazily import all components
    const components = import.meta.glob('./components/*.tsx');

Expected Behavior

Knip should parse and resolve these patterns into a list of file paths. Each resolved file should be treated as a dependency, correctly marking the files as used and tracing their exports.

Why This is Useful

  • Eliminates False Positives: Stops Knip from incorrectly flagging files imported via these mechanisms as unused.
  • Aligns with Tooling: This functionality exists in webpack, Vite, and projects using custom resolver plugins (e.g. esbuild-plugin-import-glob or rollup-plugin-glob-import)
  • Zero-Config Support: This would work out of the box without requiring new configuration options.

Real-World Use Cases

  1. Vite Glob Imports: (See examples on GitHub)
  2. Webpack Context: (See examples on GitHub)
  3. ES6-style Glob Imports: (See examples on GitHub)

Links

I'm open to working on implementing this feature if the maintainers are interested.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions