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 🙏

© 2026 – Pkg Stats / Ryan Hefner

vite-import-replacer

v0.0.3

Published

Vite import replacement engine with shared policy registration, dependency optimizer integration, and build-time resolvers

Readme

vite-import-replacer

A rule-driven, framework-independent import-rewriting engine for Vite 8. Replace an entire static module, move selected named imports and re-exports, or compute each destination using a build-time resolver. Includes an opt-in third-party dependency optimizer adapter, a shared plugin registration service, and explicit package protections.

npm install -D vite-import-replacer

The package uses TypeScript to parse source at build time. Supported Node and Vite versions are specified in package.json (vite@^8 peer). All examples below use the public API.

Start here: three transformations

Redirect an entire library

import { defineConfig } from 'vite';
import { importReplacer } from 'vite-import-replacer';

export default defineConfig({
  plugins: [importReplacer({
    replace: [{ from: 'old-library', to: 'new-library' }],
  })],
});

Omitting imports redirects the module specifier in supported static imports and export-from declarations. This preserves existing bindings and aliases, including default imports, namespace imports, named imports, side-effect imports, type imports, export { ... } from, and export * from. The destination must expose compatible exports and side effects.

// Before
import Default from 'old-library';
import * as helpers from 'old-library';
import { value as localValue } from 'old-library';
import 'old-library';
export * from 'old-library';

// After: every 'old-library' specifier above becomes 'new-library'.

Replace selected names (create*)

import { importReplacer, glob } from 'vite-import-replacer';

importReplacer({
  replace: [{
    from: 'old-library',
    imports: glob('create*'),
    to: 'new-library',
  }],
});
// Before
import { createSignal as signal, createStore, batch } from 'old-library';
// After
import { batch } from 'old-library';
import { createSignal as signal, createStore } from 'new-library';

imports matches the original exported name, not the local alias. Type-only symbols remain with the original module in named-symbol mode. imports: glob('*') selects every supported named value import/re-export from that source.

Compute a destination with resolve

import { importReplacer, glob } from 'vite-import-replacer';

importReplacer({
  replace: [{
    from: 'old-library',
    imports: glob('create*'),
    cacheKey: 'create-to-make-v1',
    resolve: ({ imported }) => ({
      module: 'new-library',
      imported: imported.replace(/^create/, 'make'),
    }),
  }],
});
// Before
import { createSignal as signal, createStore, batch } from 'old-library';
// After
import { batch } from 'old-library';
import { makeSignal as signal, makeStore as createStore } from 'new-library';

A resolver runs at build time for each matching named value import/re-export, not in the browser. It can return a module string, { module, imported? }, or null (leave this symbol unchanged). to and resolve are mutually exclusive. A nonempty cacheKey is required for resolver rules: change it whenever the function or captured lookup data changes so Vite does not use an out-of-date dependency optimization cache. Resolver behavior must be deterministic for the same inputs.

Rules and matching

One replace array is used by the app and by registered integrations:

import { glob, regex } from 'vite-import-replacer';

const replace = [
  { id: 'module', from: 'old-library', to: 'new-library' },
  { id: 'name', from: ['solid-js', '@solidjs/signals'], imports: 'createSignal', to: 'solid2-signals/priority', priority: 1 },
  { from: glob('old-library/**'), imports: regex('create[A-Z].*'), to: { module: 'new-library', imported: 'factory' } },
];

Matcher types:

| Expression | Meaning | | --- | --- | | 'solid-js' | Exact entire value (always literal, even if it contains *) | | glob('@acme/*') | Glob within one path segment | | glob('solid-js/**') | Zero or more descendant segments | | glob('**/*.test.ts') | Test files at root or deeper levels | | regex('create[A-Z].*') | Full-value regular expression | | /^create[A-Z].*$/ | Equivalent native RegExp | | ['solid-js', '@solidjs/signals'] | Match any of these values |

Globs support * (zero or more chars except /), ? (one char except /), ** (including slashes), and **/ (zero or more whole segments). Regular expressions are matched against the entire value; g and y flags are rejected because they are stateful. Every matcher is validated when options or registrations are compiled.

For named rules, to: 'new-library' preserves the imported name; to: { module: 'new-library', imported: 'renamed' } changes the imported/exported source name while preserving local and outward aliases. Exact/arrays/globs/regex work in from, imports, scopes, protections and permissions.

Priority and overlap: an explicit higher integer priority wins. At equal priority, matching named-symbol rules take precedence over module-wide rules for the same named binding. For equally specific candidate rules, an exact matcher outranks a glob, which outranks a regex. Equally ranked conflicting destinations throw instead of silently depending on registration order. Output of a rule is not reprocessed by the same pass.

Narrow a rule with only

{
  from: 'old-library', imports: glob('create*'), to: 'new-library',
  only: {
    target: 'dependencies',
    owners: glob('@acme/*'),
    files: { exclude: glob('**/*.test.ts') },
    environments: ['client'],
  },
}

only intersects the already eligible scope. It does not independently opt any dependency into processing.

Scope: which files can be transformed?

Application source is included by default. Third-party packages are not transformed unless selected by owning package name:

const imports = createImportReplacer({
  scope: {
    app: true,
    dependencies: {
      include: ['@acme/ui', glob('@acme/components-*')],
      exclude: ['@acme/native-signals'],
    },
    files: { exclude: glob('**/*.test.ts') },
    environments: ['client'], // default; add 'ssr' explicitly if appropriate
  },
});

dependencies.include matches the nearest resolved package.json owner, not the text in the node_modules folder path. This includes scoped packages, pnpm layouts and linked workspaces. File globs match POSIX-normalized paths relative to the owning package root (to the application root for app files). For instance, glob('**/*.test.ts') excludes an app test and a selected dependency's test file.

dependencies.exclude and scope.files.exclude take precedence over any permission allow. Merely selecting a protected package does not override its registered protection.

Shared service: integrations register their own rules and protections

import { defineConfig } from 'vite';
import { createImportReplacer, glob } from 'vite-import-replacer';

const imports = createImportReplacer({
  scope: { dependencies: { include: ['@acme/ui'] } },
});

// Normally a framework plugin registers this synchronously during config setup.
imports.register({
  id: 'solid2-signals',
  replace: [{
    from: ['solid-js', '@solidjs/signals'],
    imports: 'createSignal',
    to: 'solid2-signals/priority',
  }],
  protect: {
    owners: ['solid2-signals', 'solid-js', glob('@solidjs/*')],
  },
});

export default defineConfig({ plugins: [imports.plugin()] });

These Solid names are an example supplied by the integrating plugin, never hardcoded in the generic replacer. protect.owners refers to the package owning the importing source file, not the package being imported. Consequently, app code can replace imports from solid-js, while source code owned by solid-js, solid2-signals, or any @solidjs/* owner stays intact.

Framework integrations can register protections without any replacements:

imports.register({
  id: 'framework-protections',
  protect: { owners: ['framework-runtime'] },
});

They can also protect individual import specifiers rather than an entire owner:

imports.register({
  id: 'runtime-boundary',
  protect: {
    imports: [{
      owners: '@acme/ui',
      from: 'internal-runtime',
      imports: glob('create*'),
      target: 'dependencies',
    }],
  },
});

Each registration must have a unique nonempty ID and meaningful replace or protect. Registrations are synchronous and must finish before Vite runs plugin config hooks, at which time the registry freezes. plugin() returns a stable Vite plugin instance. Each createImportReplacer() service is isolated from other instances.

Permissions: selective allow/deny and deliberate protection overrides

const imports = createImportReplacer({
  scope: { dependencies: { include: [glob('@acme/*')] } },
  permissions: [
    { owner: '@acme/ui', from: glob('**'), imports: glob('*'), action: 'deny' },
    { owner: '@acme/ui', from: 'solid-js', imports: 'createSignal', action: 'allow' },
  ],
});

More specific permissions outrank broader permissions at the same priority, and a deny wins a tie. An allow does not create a replacement rule or select a dependency by itself. imports omitted from a permission covers all supported static forms, including default/namespace/side-effect.

To deliberately rewrite a protected library's own code:

const imports = createImportReplacer({
  scope: { dependencies: { include: ['solid2-signals'] } },
  permissions: [{
    owner: 'solid2-signals',
    from: 'solid-js',
    imports: 'createSignal',
    action: 'allow',
    overrideProtection: true,
  }],
});

This requires both inclusion of the protected dependency and an explicit matching allow with overrideProtection: true. It is intentionally dangerous: overriding native framework imports can create circular dependencies. A hard scope exclusion remains effective even with an override.

Decision order: unsafe asset/virtual IDs → environment → global file/dependency scope → only rule restrictions → matching permissions → registered protections → replacement rules. Diagnostic decisions can be inspected with explain().

Diagnostics, explain, reports

const result = imports.explain({
  id: '/project/node_modules/@acme/ui/index.js',
  from: 'solid-js',
  imported: 'createSignal',
  pipeline: 'optimizer',
  environment: 'client',
});
// result.decision: 'replace' | 'skip' | 'error'
// result.reason: 'REPLACEMENT', 'OWNER_PROTECTED',
// 'IMPORT_PROTECTED', 'SCOPE_EXCLUDED', 'PERMISSION_DENIED', etc.

const changed = imports.transform("import { createSignal } from 'solid-js'", {
  id: '/project/src/app.ts',
  pipeline: 'source',
  environment: 'client',
}); // { code, map } | null

const report = imports.report();
// { fingerprint, registrations, transformed, skipped, optimizerHits, diagnostics }

diagnostics may be 'off', 'summary' (default-style grouped storage), or 'verbose' (individual diagnostic entries), and controls what is retained in report(). It does not enable logging of entire files. Fatal errors throw regardless of diagnostic mode.

fingerprint() hashes the canonical policy, matchers, registrations, protection, permissions, project root and resolver cacheKey. It can be used to distinguish optimizer configurations. A callback's captured data is not automatically detected: bump the cacheKey when it changes.

Pure transformation API (/core)

import { transformImports, glob, regex } from 'vite-import-replacer/core';

const result = transformImports(
  "import { log as record } from 'old-logger';",
  {
    id: '/project/src/app.ts',
    replace: [{
      from: 'old-logger',
      imports: 'log',
      to: { module: 'new-logger', imported: 'writeLog' },
    }],
    onDiagnostic: (diagnostic) => console.warn(diagnostic.code),
  },
);

This API has no runtime dependency on Vite or Node filesystem operations. It applies syntax transformations only: it does not resolve package owners or service protections/permissions. A resolver receives owner: null when used through the pure core.

TypeScript API reference

The package ships declarations for both entry points. Root-level exports:

| Export | Description | | --- | --- | | importReplacer(options): Plugin | Standalone Vite plugin | | createImportReplacer(options?): ImportReplacerService | Shared integration service | | glob(pattern), regex(source, flags?) | Declarative matcher helpers | | Matcher, MatchInput | Exact, glob, regex or matcher array | | Destination | Module string or { module, imported? } | | ReplaceRule, ReplaceRuleBase | Union of module/named/resolved rules; common fields | | ModuleRedirectRule | { from, to }, static whole-module redirect | | NamedReplaceRule | { from, imports, to }, selected named symbols | | ResolvedReplaceRule | { from, imports, resolve, cacheKey }, computed named symbols | | ResolveImportContext, ResolvedDestination | Resolver parameter and return | | Target, FileFilter, RuleFilter | Scope restriction types | | ImportSelection, Protection, Registration | Integration protection and registration types | | DependencyScope, Scope, Permission | Application owner/file selection and permissions | | ImportReplacerOptions | Main configuration object | | TransformRequest, TransformResult, SourceMap | Service transform input/output | | ExplainRequest, ExplainResult | Explain decisions | | ImportReplacerReport, Diagnostic | Structured counters and diagnostics | | CoreTransformOptions | Pure transformImports() options | | ImportReplacerService | Service methods described below |

Core types

type Matcher = string | { readonly glob: string } | { readonly regex: string; readonly flags?: string } | RegExp;
type MatchInput = Matcher | readonly Matcher[];
type Destination = string | { readonly module: string; readonly imported?: string };

type ReplaceRule =
  | ModuleRedirectRule    // from + to (whole module)
  | NamedReplaceRule      // from + imports + to
  | ResolvedReplaceRule;  // from + imports + resolve + cacheKey

interface ReplaceRuleBase {
  readonly id?: string;
  readonly from: MatchInput;
  readonly priority?: number;
  readonly only?: RuleFilter;
}
interface RuleFilter {
  readonly target?: 'app' | 'dependencies' | 'all';
  readonly owners?: MatchInput;
  readonly files?: { readonly include?: MatchInput; readonly exclude?: MatchInput };
  readonly environments?: readonly string[];
}
interface ResolveImportContext {
  readonly imported: string;
  readonly from: string;
  readonly importer: string;
  readonly owner: string | null;
  readonly kind: 'import' | 'reexport';
  readonly environment: string;
}

Scope, policy and service types

interface Scope {
  readonly app?: boolean;
  readonly dependencies?: { include?: MatchInput; exclude?: MatchInput };
  readonly files?: { include?: MatchInput; exclude?: MatchInput };
  readonly environments?: readonly string[];
}
interface Protection {
  readonly owners?: MatchInput;
  readonly imports?: readonly {
    from: MatchInput;
    imports?: MatchInput;
    target?: 'app'|'dependencies'|'all';
    owners?: MatchInput;
  }[];
}
interface Permission {
  readonly action: 'allow' | 'deny';
  readonly owner?: MatchInput;
  readonly target?: 'app' | 'dependencies' | 'all';
  readonly from: MatchInput;
  readonly imports?: MatchInput;
  readonly priority?: number;
  readonly overrideProtection?: boolean;
}
interface ImportReplacerOptions {
  readonly replace?: readonly ReplaceRule[];
  readonly scope?: Scope;
  readonly permissions?: readonly Permission[];
  readonly diagnostics?: 'off' | 'summary' | 'verbose';
  readonly root?: string;
}
interface ImportReplacerService {
  register(registration: Registration): void;
  plugin(): import('vite').Plugin;
  transform(code: string, request: TransformRequest): TransformResult | null;
  explain(request: ExplainRequest): ExplainResult;
  fingerprint(): string;
  report(): ImportReplacerReport;
}

TransformRequest is { id, pipeline?: 'source' | 'optimizer', environment?: string }. ExplainRequest adds { from, imported? }. ExplainResult reports { decision, reason, owner, target?, registrationId?, ruleId?, matchedPermissions, matchedProtections }. TransformResult is { code, map }, where map is a standard version-3 source map with file, sources, sourcesContent, names and mappings; null means no changes. Diagnostics use { code, severity, message, id? }.

The /core subpath exports transformImports, validateRules, glob, regex, compileMatcher, bestMatch and the framework-independent types. All Vite-specific registration and scope types are available from the package root.

Vite dependency optimizer and SSR

In normal development and production, the Vite adapter uses a pre-transform hook. In Vite 8 development, dependencies can be processed in a separate Rolldown pre-bundling pass; the plugin also contributes an optimizer hook through optimizeDeps.rolldownOptions.plugins. Both hooks reuse the same scope, registered replacements, protections and permissions. Existing optimizer plugins are expected to be merged by Vite. Only explicitly selected third-party owners are candidates.

The optimizer fingerprint includes rule configuration, matcher patterns, protections, scopes, permissions and resolver cache keys. Ordinary editing of resolver closure state is not independently observable: update cacheKey when changes should invalidate optimized dependencies. Vite's separate optimizeDeps.exclude setting disables prebundling and is not equivalent to an import-replacer exclusion.

SSR is excluded by default; add 'ssr' to scope.environments to opt in. Externalized SSR dependencies may still never pass through Vite's transform hook; configure ssr.noExternal where needed and test in your environment.

Behavior and limits

  • Supported: ES static import declarations (including default, namespace, side-effect and import type for whole-module redirects); named value imports and named re-exports (including aliases) for symbol rules; static export * from with module rules; TS, TSX, JS, JSX parsing; actual v3 source maps.
  • Not rewritten: CommonJS require(), dynamic import(), import.meta, already prebundled/minified vendor output, per-symbol renaming of default/namespace bindings, type-only bindings in named-symbol rules.
  • Unsafe targets (virtual IDs, ?raw/?url/workers, assets, generated Vite optimizer output) are skipped. Import attributes that require splitting and declarations containing unsafe intra-binding comments are left intact with diagnostics; ordinary whole-module redirects only edit the source specifier.
  • Resolver output must name a valid module and imported identifier. Resolver callbacks are build-time only. Avoid using them for non-deterministic mappings or importing code with side effects.
  • Rewritten code assumes destination modules provide the selected exports. The engine does not perform semantic equivalence or runtime compatibility checks. For unsupported dependency module formats, verify behavior in actual Vite dev/build pipelines before enabling them.