Skip to content

Instantly share code, notes, and snippets.

@lazuee
Created January 24, 2025 12:38
Show Gist options
  • Save lazuee/15d87f7a71e130eb4c6e87939f75c8e8 to your computer and use it in GitHub Desktop.
Save lazuee/15d87f7a71e130eb4c6e87939f75c8e8 to your computer and use it in GitHub Desktop.
Load configuration file
import { loadConfigFile } from "./load";
const { config } = await loadConfigFile("custom.config"); // custom.config.(?:json|[cm]?[tj]s)
console.log(config);
import { promises as fsp } from "node:fs";
import { dirname, resolve } from "node:path";
import { loadConfig, LoadConfigOptions, LoadConfigResult } from "unconfig";
type MaybePromise<T> = T | Promise<T>
export async function getResolvedFilePath(filePath: string): Promise<[cwd: string, filePath: string, isOverride: boolean]> {
let currentDir = process.cwd();
let isOverride = false;
const stat = await fsp.stat(filePath).catch(() => null);
if (stat) {
const absolutePath = resolve(filePath);
if (stat.isFile()) {
isOverride = true;
filePath = absolutePath;
currentDir = dirname(filePath);
} else {
currentDir = absolutePath;
}
}
return [currentDir, filePath, isOverride];
}
export async function loadConfigFile<T>(
filePath: string,
options?: LoadConfigOptions<T> | ((opts: LoadConfigOptions<T>, filePath: string, isOverride: boolean) => MaybePromise<LoadConfigOptions<T>>)
): Promise<LoadConfigResult<T>> {
const [cwd, resolvedFilePath, isOverride] = await getResolvedFilePath(filePath);
const sources = isOverride
? [{ files: filePath, extensions: [] }]
: [{ files: resolvedFilePath }];
options = typeof options === "function"
? await options({ cwd, sources }, resolvedFilePath, isOverride)
: { ...options, sources: Array.isArray(options?.sources) && options.sources?.length ? options.sources : sources };
return loadConfig<T>({ cwd, ...options });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment