Skip to content

Commit 4e16b82

Browse files
authored
feat: support .config dir (#136)
1 parent 593619a commit 4e16b82

File tree

5 files changed

+19
-10
lines changed

5 files changed

+19
-10
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ c12 (pronounced as /siːtwelv/, like c-twelve) is a smart configuration loader.
1313
## ✅ Features
1414

1515
- `.js`, `.ts`, `.cjs`, `.mjs` config loader with [unjs/jiti](https://github.com/unjs/jiti)
16-
- `.json`, `.json5` and `.jsonc` config support.
16+
- `.json`, `.json5` and `.jsonc` config support
17+
- `.config/` directory support following [config dir proposal](https://github.com/pi0/config-dir)
1718
- `.rc` config support with [unjs/rc9](https://github.com/unjs/rc9)
1819
- `.env` support with [dotenv](https://www.npmjs.com/package/dotenv)
1920
- Multiple sources merged with [unjs/defu](https://github.com/unjs/defu)

src/loader.ts

+16-8
Original file line numberDiff line numberDiff line change
@@ -298,11 +298,16 @@ async function resolveConfig<
298298
source = cloned.dir;
299299
}
300300

301-
// Try resolving as npm package
302-
if (NPM_PACKAGE_RE.test(source)) {
301+
// Util to try resolving a module
302+
const tryResolve = (id: string) => {
303303
try {
304-
source = options.jiti!.resolve(source, { paths: [options.cwd!] });
304+
return options.jiti!.resolve(id, { paths: [options.cwd!] });
305305
} catch {}
306+
};
307+
308+
// Try resolving as npm package
309+
if (NPM_PACKAGE_RE.test(source)) {
310+
source = tryResolve(source) || source;
306311
}
307312

308313
// Import from local fs
@@ -314,19 +319,22 @@ async function resolveConfig<
314319
}
315320
const res: ResolvedConfig<T, MT> = {
316321
config: undefined as unknown as T,
322+
configFile: undefined,
317323
cwd,
318324
source,
319325
sourceOptions,
320326
};
321-
try {
322-
res.configFile = options.jiti!.resolve(resolve(cwd, source), {
323-
paths: [cwd],
324-
});
325-
} catch {}
327+
328+
res.configFile =
329+
tryResolve(resolve(cwd, source)) ||
330+
tryResolve(resolve(cwd, ".config", source.replace(/\.config$/, ""))) ||
331+
tryResolve(resolve(cwd, ".config", source)) ||
332+
source;
326333

327334
if (!existsSync(res.configFile!)) {
328335
return res;
329336
}
337+
330338
if (res.configFile!.endsWith(".jsonc")) {
331339
const { parse } = await import("jsonc-parser");
332340
res.config = parse(await readFile(res.configFile!, "utf8"));
File renamed without changes.

test/index.test.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ describe("c12", () => {
144144
"secondary": "theme_secondary",
145145
},
146146
},
147-
"configFile": "<path>/fixture/theme/test.config.json5",
147+
"configFile": "<path>/fixture/theme/.config/test.config.json5",
148148
"cwd": "<path>/fixture/theme",
149149
"meta": {},
150150
"source": "test.config",

0 commit comments

Comments
 (0)