lilconfig icon indicating copy to clipboard operation
lilconfig copied to clipboard

Support `.ts` like cosmiconfig

Open felipecrs opened this issue 5 months ago • 2 comments

  • Refs https://github.com/cosmiconfig/cosmiconfig/pull/311

However, as Node 22.18+ now supports reading .ts by default, then maybe there is no need to depend on TypeScript.

felipecrs avatar Aug 05 '25 17:08 felipecrs

Might help others, I was able to add .ts support in userland by using jiti, something like:

import type { Loader } from "lilconfig";

import { lilconfig } from "lilconfig";

const loadTs: Loader = async (filepath) => {
  const { createJiti } = await import("jiti");

  return createJiti(import.meta.url, { interopDefault: true }).import(
    filepath,
    {
      default: true,
    },
  );
};

export async function loadConfig(name: string) {
  const explorer = lilconfig(name, {
    loaders: {
      ".mts": loadTs,
      ".ts": loadTs,
    },
    searchPlaces: [
      `${name}.config.ts`,
      `${name}.config.mts`,
    ],
  });

  return explorer.search(process.cwd());
}

Or without jiti

import { pathToFileURL } from "node:url";

import type { Loader } from "lilconfig";

import { lilconfig } from "lilconfig";

const loadTs: Loader = async (filepath) => {
  const url = pathToFileURL(filepath).href;
  const mod = await import(url);

  return mod.default ?? mod;
};

export async function loadConfig(name: string) {
  const explorer = lilconfig(name, {
    loaders: {
      ".mts": loadTs,
      ".ts": loadTs,
    },
    searchPlaces: [
      `${name}.config.ts`,
      `${name}.config.mts`,
    ],
  });

  return explorer.search(process.cwd());
}

jimmy-guzman avatar Nov 19 '25 12:11 jimmy-guzman

If process.features.typescript (v22.18.0+ or v22.6.0+ with flag) is truthy, await import could be attempted automatically if there is no existing loader configured for .ts or .mts.

silverwind avatar Dec 15 '25 19:12 silverwind