Cosmiconfig TypeScript Loader

6.3.0 · active · verified Sun Apr 19

cosmiconfig-typescript-loader provides a robust TypeScript loader for `cosmiconfig`, enabling applications to load configuration files written in TypeScript (e.g., `.ts` files). It is currently at version 6.3.0, with minor and patch releases occurring as needed for dependency updates and maintenance. This package serves as a maintained successor to the abandoned `@endemolshinegroup/cosmiconfig-typescript-loader`, addressing several critical issues found in the original, such as compatibility with `cosmiconfig`'s synchronous API and providing proper TypeScript support during compilation. It leverages `jiti` for on-the-fly TypeScript compilation, supporting both CommonJS and ESM environments, making it a flexible choice for modern Node.js applications that rely on TypeScript for configuration.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to integrate `cosmiconfig-typescript-loader` into a `cosmiconfig` explorer to asynchronously load a TypeScript configuration file, defining its structure with an interface.

import { cosmiconfig } from "cosmiconfig";
import { TypeScriptLoader } from "cosmiconfig-typescript-loader";

interface MyConfig {
  host: string;
  port: number;
  enabledFeatures?: string[];
}

async function loadConfig(): Promise<MyConfig | null> {
  const moduleName = "my-app";
  const explorer = cosmiconfig(moduleName, {
    searchPlaces: [
      `${moduleName}.config.ts`,
      `.${moduleName}rc.ts`
    ],
    loaders: {
      ".ts": TypeScriptLoader(),
    },
  });

  // Assume 'my-app.config.ts' exists in the current directory with content like:
  // export default { host: 'localhost', port: 3000 };
  try {
    const result = await explorer.load(process.cwd());
    if (result && result.config) {
      console.log("Configuration loaded successfully:", result.config);
      return result.config as MyConfig;
    } else {
      console.log("No configuration found.");
      return null;
    }
  } catch (error) {
    console.error("Error loading configuration:", error);
    throw error;
  }
}

loadConfig();

view raw JSON →