diff --git a/README.md b/README.md index 8a54dce..320f7fb 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,8 @@ c12 (pronounced as /siːtwelv/, like c-twelve) is a smart configuration loader. ## ✅ Features - `.js`, `.ts`, `.cjs`, `.mjs` config loader with [unjs/jiti](https://github.com/unjs/jiti) -- `.json`, `.json5` and `.jsonc` config support. +- `.json`, `.json5` and `.jsonc` config support +- `.config/` directory support following [config dir proposal](https://github.com/pi0/config-dir) - `.rc` config support with [unjs/rc9](https://github.com/unjs/rc9) - `.env` support with [dotenv](https://www.npmjs.com/package/dotenv) - Multiple sources merged with [unjs/defu](https://github.com/unjs/defu) diff --git a/src/loader.ts b/src/loader.ts index edc7455..5f71b74 100644 --- a/src/loader.ts +++ b/src/loader.ts @@ -298,11 +298,16 @@ async function resolveConfig< source = cloned.dir; } - // Try resolving as npm package - if (NPM_PACKAGE_RE.test(source)) { + // Util to try resolving a module + const tryResolve = (id: string) => { try { - source = options.jiti!.resolve(source, { paths: [options.cwd!] }); + return options.jiti!.resolve(id, { paths: [options.cwd!] }); } catch {} + }; + + // Try resolving as npm package + if (NPM_PACKAGE_RE.test(source)) { + source = tryResolve(source) || source; } // Import from local fs @@ -314,19 +319,22 @@ async function resolveConfig< } const res: ResolvedConfig = { config: undefined as unknown as T, + configFile: undefined, cwd, source, sourceOptions, }; - try { - res.configFile = options.jiti!.resolve(resolve(cwd, source), { - paths: [cwd], - }); - } catch {} + + res.configFile = + tryResolve(resolve(cwd, source)) || + tryResolve(resolve(cwd, ".config", source.replace(/\.config$/, ""))) || + tryResolve(resolve(cwd, ".config", source)) || + source; if (!existsSync(res.configFile!)) { return res; } + if (res.configFile!.endsWith(".jsonc")) { const { parse } = await import("jsonc-parser"); res.config = parse(await readFile(res.configFile!, "utf8")); diff --git a/test/fixture/test.config.ts b/test/fixture/.config/test.ts similarity index 100% rename from test/fixture/test.config.ts rename to test/fixture/.config/test.ts diff --git a/test/fixture/theme/test.config.json5 b/test/fixture/theme/.config/test.config.json5 similarity index 100% rename from test/fixture/theme/test.config.json5 rename to test/fixture/theme/.config/test.config.json5 diff --git a/test/index.test.ts b/test/index.test.ts index d1c1da5..548bfef 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -144,7 +144,7 @@ describe("c12", () => { "secondary": "theme_secondary", }, }, - "configFile": "/fixture/theme/test.config.json5", + "configFile": "/fixture/theme/.config/test.config.json5", "cwd": "/fixture/theme", "meta": {}, "source": "test.config",