# @hyperse/config-loader

> A TypeScript path alias resolver for Node.js applications that works seamlessly with both development (config-loader) and production environments. This package automatically resolves path aliases based on your `tsconfig.json` configuration, eliminating th

Latest version **1.0.10** (published 2026-10-15) · 0 weekly downloads

## Install

```sh
npm install @hyperse/config-loader
pnpm add @hyperse/config-loader
yarn add @hyperse/config-loader
bun add @hyperse/config-loader
```

## Health

**Score 70/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; recently updated; high maintenance score; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 1.0.10 |
| Published | 2026-10-15 |
| First published | 2025-06-05 |
| Weekly downloads | 0 |
| TypeScript types | bundled |
| Module format | ESM |
| Node | >=22.11.0 |
| Dependencies | 7 |
| Unpacked size | 52.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 3 |
| Maintainers | tianyingchun, hyperse.net |
| Keywords | hyperse, typescript, esm, config loader, cjs, type:module |

## Links

- npm: https://www.npmjs.com/package/@hyperse/config-loader
- Repository: git@github.com:hyperse-io/config-loader
- npm.io page: https://npm.io/package/@hyperse/config-loader

## Dependencies (7)

- [rollup](https://npm.io/package/rollup.md) ^4.64.6
- [@swc/core](https://npm.io/package/@swc/core.md) ^1.16.18
- [cosmiconfig](https://npm.io/package/cosmiconfig.md) ^10.0.1
- [get-tsconfig](https://npm.io/package/get-tsconfig.md) ^4.14.3
- [@hyperse/deep-merge](https://npm.io/package/@hyperse/deep-merge.md) ^1.0.2
- [@hyperse/unplugin-swc](https://npm.io/package/@hyperse/unplugin-swc.md) ^2.0.0
- [@manypkg/get-packages](https://npm.io/package/@manypkg/get-packages.md) ^3.1.0

## Alternatives

- [@openai/codex-sdk](https://npm.io/package/@openai/codex-sdk.md) — 731.4K weekly downloads
- [babel-plugin-transform-react-jsx](https://npm.io/package/babel-plugin-transform-react-jsx.md) — 565.0K weekly downloads
- [babel-helper-remove-or-void](https://npm.io/package/babel-helper-remove-or-void.md) — 508.5K weekly downloads
- [@pnpm/store-controller-types](https://npm.io/package/@pnpm/store-controller-types.md) — 186.9K weekly downloads
- [react-native-signature-canvas](https://npm.io/package/react-native-signature-canvas.md) — 155.6K weekly downloads

## Recent versions

- 1.0.10 (latest) — 2026-10-15
- 1.0.9 — 2026-03-22
- 1.0.8 — 2026-01-14
- 1.0.7 — 2025-09-22
- 1.0.6 — 2025-07-06
- 1.0.5 — 2025-06-09
- 1.0.4 — 2025-06-09
- 1.0.3 — 2025-06-06
- 1.0.2 — 2025-06-05
- 1.0.1 — 2025-06-05

## README

# @hyperse/config-loader

A config loader that searches for and loads configuration files for your program, with support for `type:module`, `esm`, and `cjs` module formats

<p align="left">
  <a aria-label="Build" href="https://github.com/hyperse-io/config-loader/actions?query=workflow%3ACI">
    <img alt="build" src="https://img.shields.io/github/actions/workflow/status/hyperse-io/config-loader/ci-integrity.yml?branch=main&label=ci&logo=github&style=flat-quare&labelColor=000000" />
  </a>
  <a aria-label="stable version" href="https://www.npmjs.com/package/@hyperse/config-loader">
    <img alt="stable version" src="https://img.shields.io/npm/v/%40hyperse%2Fconfig-loader?branch=main&label=version&logo=npm&style=flat-quare&labelColor=000000" />
  </a>
  <a aria-label="Top language" href="https://github.com/hyperse-io/config-loader/search?l=typescript">
    <img alt="GitHub top language" src="https://img.shields.io/github/languages/top/hyperse-io/config-loader?style=flat-square&labelColor=000&color=blue">
  </a>
  <a aria-label="Licence" href="https://github.com/hyperse-io/config-loader/blob/main/LICENSE">
    <img alt="Licence" src="https://img.shields.io/github/license/hyperse-io/config-loader?style=flat-quare&labelColor=000000" />
  </a>
</p>

The config loader is a powerful utility that searches for and loads configuration files for your JavaScript/TypeScript applications. It automatically handles multiple file formats and module systems while providing type safety.

Built on top of cosmiconfig, it implements smart defaults aligned with JavaScript ecosystem conventions, while remaining highly configurable. You can customize search paths, file formats, and loading behavior to match your specific needs.

## Features

- 🔍 Automatic config file resolution with support for multiple formats (JSON, YAML, JS, TS)
- 🎯 Flexible configuration search across multiple file locations
- 🚀 ESM and CommonJS module support
- 🔧 TypeScript configuration with full type inference
- ⚡️ Built on top of cosmiconfig for reliable config loading
- 🧪 Well-tested and production-ready
- 🔄 Automatic resolution of TypeScript path aliases from tsconfig.json
- 🔗 Smart handling of external modules and dependencies
- 📦 Automatically marks package.json dependencies and devDependencies as external
- 🏗️ Built-in support for monorepo setups and workspace packages

## Installation

```bash
npm install --save @hyperse/config-loader
```

## API Reference

### `searchConfig<T>(moduleName: string, searchFrom?: string, options?: LoaderOptions)`

Searches up the directory tree for configuration files, checking multiple locations in each directory until it finds a valid configuration or reaches the home directory.

**Parameters:**

- `moduleName` (string): Your module name. Used to create default search places and package properties
- `searchFrom` (string, optional): Directory to start searching from. Defaults to `process.cwd()`
- `options` (LoaderOptions, optional): Configuration options for the loader

**Returns:** Promise<ConfigLoadResult<T> | null>

**Example:**

```typescript
import { searchConfig } from '@hyperse/config-loader';

// Search for a config file named 'myapp'
const result = await searchConfig<{
  port: number;
  database: {
    url: string;
  };
}>('myapp');

if (result) {
  console.log(result.config.port); // Access the loaded config
}
```

### `loadConfig<T>(configFile: string, options?: LoaderOptions)`

Loads a configuration file from a specific path.

**Parameters:**

- `configFile` (string): Path to the configuration file
- `options` (LoaderOptions, optional): Configuration options for the loader

**Returns:** Promise<ConfigLoadResult<T> | null>

**Example:**

```typescript
import { loadConfig } from '@hyperse/config-loader';

// Load a specific config file
const result = await loadConfig<{
  port: number;
  database: {
    url: string;
  };
}>('./config/myapp.config.ts');

if (result) {
  console.log(result.config.port);
}
```

### `mergeOptions<T>(target: T, source: DeepPartial<T>, mergeUndefined?: boolean)`

Performs a deep merge of two configuration objects. Unlike `Object.assign()`, the target object is not mutated.

**Parameters:**

- `target` (T): The target object to merge into
- `source` (DeepPartial<T>): The source object to merge from
- `mergeUndefined` (boolean, optional): Whether to merge undefined values. Defaults to false

**Returns:** T (new merged object)

**Example:**

```typescript
import { mergeOptions } from '@hyperse/config-loader';

const defaultConfig = {
  server: {
    port: 3000,
    host: 'localhost',
  },
  database: {
    url: 'postgres://localhost:5432/mydb',
    pool: {
      min: 0,
      max: 10,
    },
  },
};

const userConfig = {
  server: {
    port: 4000,
  },
  database: {
    pool: {
      max: 20,
    },
  },
};

const mergedConfig = mergeOptions(defaultConfig, userConfig);
// Result:
// {
//   server: {
//     port: 4000,
//     host: 'localhost'
//   },
//   database: {
//     url: 'postgres://localhost:5432/mydb',
//     pool: {
//       min: 0,
//       max: 20
//     }
//   }
// }
```

### `defineConfig<T, ConfigEnv extends ConfigEnvBase = ConfigEnvBase>`

A type helper for defining configuration objects with proper typing and environment support.

**Example:**

```typescript
import { defineConfig } from '@hyperse/config-loader';

interface MyConfig {
  port: number;
  database: {
    url: string;
  };
}

interface MyConfigEnv {
  mode: 'development' | 'production';
}

export default defineConfig<MyConfig, MyConfigEnv>((env) => {
  return {
    port: env.mode === 'production' ? 80 : 3000,
    database: {
      url:
        env.mode === 'production'
          ? 'postgres://prod:5432/mydb'
          : 'postgres://localhost:5432/mydb',
    },
  };
});
```

### LoaderOptions

Configuration options for the loader:

```typescript
interface LoaderOptions {
  // Project root directory
  projectCwd?: string;
  // Path to tsconfig.json
  tsconfig?: string;
  // Additional plugins
  plugins?: Plugin[];
  // External dependencies to exclude
  externals?: Array<RegExp | string>;
  // The function to exclude aggregated externals, if the function returns true, the module will be excluded.
  externalExclude?: (moduleId: RegExp | string) => boolean;
  // The function to create your custom loaders.
  createLoaders?: (
    options?: LoaderOptions,
    searchFrom?: string
  ) => ConfigLoaders;
}
```

#### Custom Loaders Options

`externalExclude` - A function to exclude specific modules from being marked as external. Takes a module ID (string or RegExp) and returns true if the module should be excluded from externalization. This is useful for keeping certain dependencies bundled even if they match the external patterns.

```typescript
import { searchConfig } from '@hyperse/config-loader';

// Example 1: Basic usage with string patterns
const result1 = await searchConfig('myapp', undefined, {
  // Default external pattern
  externals: ['@hyperse/ts-node'],
  externalExclude: (moduleId) => {
    // Don't exclude modules that match these patterns
    if (typeof moduleId === 'string') {
      return !(
        moduleId.includes('@myorg/') || moduleId.includes('my-local-package')
      );
    }
    return true;
  },
});

// Example 2: Advanced usage with RegExp patterns
const result2 = await searchConfig('myapp', undefined, {
  // Multiple external patterns
  externals: ['@hyperse/ts-node', /^@vendor\//],
  externalExclude: (moduleId) => {
    if (typeof moduleId === 'string') {
      // Exclude specific packages from being marked as external
      return (
        moduleId.includes('@myorg/shared-utils') ||
        moduleId.includes('internal-tools')
      );
    }
    // For RegExp patterns, check specific module names
    return (
      moduleId.test('@myorg/shared-utils') || moduleId.test('internal-tools')
    );
  },
});
```

`createLoaders` - You can create custom loaders to handle specific file formats or add custom loading logic. Here's an example of how to create a custom loader for `.toml` files:

```typescript
import { readFile } from 'fs/promises';
import {
  type ConfigLoaders,
  type LoaderOptions,
  searchConfig,
} from '@hyperse/config-loader';
import { parse } from '@iarna/toml';

// Create a custom loader for TOML files
const createTomlLoader = (
  options?: LoaderOptions,
  searchFrom?: string
): ConfigLoaders => {
  return {
    '.toml': async (filepath: string) => {
      try {
        const content = await readFile(filepath, 'utf-8');
        const config = parse(content);
        return { config, filepath };
      } catch (error) {
        throw new Error(
          `Failed to load TOML config from ${filepath}: ${error.message}`
        );
      }
    },
  };
};

// Use the custom loader
const result = await searchConfig('myapp', undefined, {
  createLoaders: createTomlLoader,
});
```

You can also reuse existing loaders from `@hyperse/config-loader`. The package exports several built-in loaders like `tsLoader`, `jsonLoader`, and `yamlLoader` that you can compose together to create custom loading behavior.

```typescript
import type { ConfigLoaders, LoaderOptions } from '@hyperse/config-loader';
import { searchConfig, tsLoader } from '@hyperse/config-loader';

// Create a custom loader for TOML files
function createJsLoader(
  options?: LoaderOptions,
  searchFrom?: string
): ConfigLoaders {
  return {
    // Override JavaScript file resolver using tsLoader for better TypeScript support
    '.js': async (path: string, content: string) => {
      const { projectCwd, ...restLoaderOptions } = options || {};
      return tsLoader({
        plugins: [],
        externals: [],
        ...restLoaderOptions,
        projectCwd: projectCwd || searchFrom,
      })(path, content);
    },
  };
}

// Use the custom loader
const result = await searchConfig('myapp', undefined, {
  createLoaders: createJsLoader,
});
```

### Supported File Formats

The config loader supports the following file formats:

- `.js` (ESM and CommonJS)
- `.mjs` (ESM)
- `.cjs` (CommonJS)
- `.ts` (TypeScript)
- `.mts` (TypeScript ESM)
- `.json`
- `.yaml`/`.yml`

The loader will search for files in the following order:

1. `package.json` (in the `[moduleName]` field)
2. `.[moduleName]rc`
3. `.[moduleName]rc.json`
4. `.[moduleName]rc.yaml`
5. `.[moduleName]rc.yml`
6. `.[moduleName]rc.js`
7. `.[moduleName]rc.mjs`
8. `.[moduleName]rc.cjs`
9. `.[moduleName]rc.ts`
10. `[moduleName].config.js`
11. `[moduleName].config.mjs`
12. `[moduleName].config.cjs`
13. `[moduleName].config.ts`
14. `[moduleName].config.mts`

---
_Source: https://npm.io/package/@hyperse/config-loader · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
