Wildcard Module Declarations Type Asset Imports

Declare wildcard modules for CSS, SVG, and virtual imports, derive module types with typeof import, and keep asset imports typed.

TypescriptConfig Management

Code

typescriptsnippet
29 lines
// Wildcard module declarations type asset imports without source files.
declare module "*.module.css" {
  const classes: Readonly<Record<string, string>>;
  export default classes;
}

declare module "*.svg?url" {
  const url: string;
  export default url;
}

declare module "virtual:build-info" {
  export const commit: string;
  export const builtAt: string;
}

type CssModule = typeof import("./button.module.css");
type SvgUrl = typeof import("./icon.svg?url");

function className(module: CssModule, key: string): string {
  return module.default[key] ?? key;
}

const styles: CssModule = { default: { button: "btn_9f2c" } };
const icon: SvgUrl = "icon.svg";

console.log("class:", className(styles, "button"));
console.log("fallback:", className(styles, "ghost"));
console.log("icon:", icon);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

class: btn_9f2c
fallback: ghost
icon: icon.svg

The mechanics behind the demo

The moving parts sit in the function className.

Points of care

  • No outside surface: every behavior comes from the standard library.

Putting it to use

Running the file prints labeled results such as class:, fallback:, icon: — each operation’s effect is visible in the output.

commit is the public entry point; everything else in the file exists to support it.

Core lines

return module.default[key] ?? key;

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `className` at load time.