Skip to content

Commit 87f89de

Browse files
committedFeb 12, 2025·
feat: allow for config file names that equal config name
1 parent c3b8a9b commit 87f89de

File tree

1 file changed

+33
-20
lines changed

1 file changed

+33
-20
lines changed
 

‎src/index.ts

+33-20
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,20 @@ import type { Config } from './types'
22
import { resolve } from 'node:path'
33
import { deepMerge } from './utils'
44

5+
/**
6+
* Attempts to load a config file from a specific path
7+
*/
8+
async function tryLoadConfig<T>(configPath: string, defaultConfig: T): Promise<T | null> {
9+
try {
10+
const importedConfig = await import(configPath)
11+
const loadedConfig = importedConfig.default || importedConfig
12+
return deepMerge(defaultConfig, loadedConfig) as T
13+
}
14+
catch {
15+
return null
16+
}
17+
}
18+
519
/**
620
* Load Config
721
*
@@ -31,33 +45,32 @@ export async function loadConfig<T>({
3145
'Content-Type': 'application/json',
3246
},
3347
}: Config<T>): Promise<T> {
34-
// If running in a server (Bun) environment, load the config from the file system
48+
// If running in a server environment, load the config from the file system
3549
if (typeof window === 'undefined') {
36-
try {
37-
// back 3 times to get out of node_modules into the root directory, assuming the config is in the root directory
38-
const configPath = resolve(cwd || '../../../', `${name}.config`)
39-
const importedConfig = await import(configPath)
40-
const loadedConfig = importedConfig.default || importedConfig
41-
42-
return deepMerge(defaultConfig, loadedConfig) as T
43-
}
44-
// eslint-disable-next-line unused-imports/no-unused-vars
45-
catch (error: any) {
46-
try {
47-
const dotConfigPath = resolve(cwd || '../../../', `.${name}.config`)
48-
const importedConfig = await import(dotConfigPath)
49-
const loadedConfig = importedConfig.default || importedConfig
50+
const baseDir = cwd || '../../../'
5051

51-
return deepMerge(defaultConfig, loadedConfig) as T
52-
}
53-
catch (error) {
54-
console.error('Failed to load client config:', error)
52+
// Try loading config in order of preference
53+
const configPaths = [
54+
`${name}.config`,
55+
`.${name}.config`,
56+
name,
57+
`.${name}`,
58+
]
5559

56-
return defaultConfig
60+
for (const configPath of configPaths) {
61+
const fullPath = resolve(baseDir, configPath)
62+
const config = await tryLoadConfig(fullPath, defaultConfig)
63+
if (config !== null) {
64+
return config
5765
}
5866
}
67+
68+
console.error('Failed to load client config from any expected location')
69+
70+
return defaultConfig
5971
}
6072

73+
// Browser environment checks
6174
if (!endpoint) {
6275
console.warn('An API endpoint is required to load the client config.')
6376
return defaultConfig

0 commit comments

Comments
 (0)
Please sign in to comment.