lilconfig
lilconfig copied to clipboard
Support `.ts` like cosmiconfig
- 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.
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());
}
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.