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.
Code
// 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.svgThe 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.