{"id":14156202,"url":"https://github.com/unjs/c12","last_synced_at":"2026-02-06T19:06:28.908Z","repository":{"id":37732750,"uuid":"452429924","full_name":"unjs/c12","owner":"unjs","description":"⚙️ Smart Configuration Loader","archived":false,"fork":false,"pushed_at":"2024-10-23T01:38:25.000Z","size":1158,"stargazers_count":521,"open_issues_count":15,"forks_count":19,"subscribers_count":4,"default_branch":"main","last_synced_at":"2024-10-24T18:37:23.344Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/unjs.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-01-26T20:29:16.000Z","updated_at":"2024-10-24T08:32:15.000Z","dependencies_parsed_at":"2023-09-24T05:10:53.864Z","dependency_job_id":"176554e2-d82d-4b45-a5be-44a84da4f6ef","html_url":"https://github.com/unjs/c12","commit_stats":{"total_commits":123,"total_committers":10,"mean_commits":12.3,"dds":0.6178861788617886,"last_synced_commit":"2b8719312c097a607648b378576477c5703c0f73"},"previous_names":["unjs/c11"],"tags_count":43,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unjs%2Fc12","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unjs%2Fc12/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unjs%2Fc12/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unjs%2Fc12/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/unjs","download_url":"https://codeload.github.com/unjs/c12/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228829090,"owners_count":17978152,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-17T08:05:17.078Z","updated_at":"2026-02-06T19:06:28.901Z","avatar_url":"https://github.com/unjs.png","language":"TypeScript","funding_links":[],"categories":["others","TypeScript"],"sub_categories":[],"readme":"# ⚙️ c12\n\n\u003c!-- automd:badges color=yellow codecov --\u003e\n\n[![npm version](https://img.shields.io/npm/v/c12?color=yellow)](https://npmjs.com/package/c12)\n[![npm downloads](https://img.shields.io/npm/dm/c12?color=yellow)](https://npm.chart.dev/c12)\n[![codecov](https://img.shields.io/codecov/c/gh/unjs/c12?color=yellow)](https://codecov.io/gh/unjs/c12)\n\n\u003c!-- /automd --\u003e\n\nc12 (pronounced as /siːtwelv/, like c-twelve) is a smart configuration loader.\n\n## ✅ Features\n\n- `.js`, `.ts`, `.mjs`, `.cjs`, `.mts`, `.cts` `.json` config loader with customizable import or [unjs/jiti](https://jiti.unjs.io) fallback.\n- `.jsonc`, `.json5`, `.yaml`, `.yml`, `.toml` config loader with [unjs/confbox](https://confbox.unjs.io)\n- `.config/` directory support ([config dir proposal](https://github.com/pi0/config-dir))\n- `.rc` config support with [unjs/rc9](https://github.com/unjs/rc9)\n- `.env` support with variable interpolation and `_FILE` references resolution\n- Multiple sources merged with [unjs/defu](https://github.com/unjs/defu)\n- Reads config from the nearest `package.json` file\n- [Extends configurations](https://github.com/unjs/c12#extending-configuration) from multiple local or git sources\n- Overwrite with [environment-specific configuration](#environment-specific-configuration)\n- Config watcher with auto-reload and HMR support\n- Create or update configuration files with [magicast](https://github.com/unjs/magicast)\n\n## 🦴 Used by\n\n- [Hey API](https://github.com/hey-api/openapi-ts)\n- [Kysely](https://github.com/kysely-org/kysely-ctl)\n- [Nitro](https://nitro.build/)\n- [Nuxt](https://nuxt.com/)\n- [Prisma](https://github.com/prisma/prisma)\n- [Trigger.dev](https://github.com/triggerdotdev/trigger.dev)\n- [UnJS](https://github.com/unjs)\n- [WXT](https://github.com/wxt-dev/wxt)\n\n## Usage\n\nInstall package:\n\n```sh\n# ✨ Auto-detect\nnpx nypm install c12\n```\n\nImport:\n\n```js\n// ESM import\nimport { loadConfig, watchConfig } from \"c12\";\n\n// or using dynamic import\nconst { loadConfig, watchConfig } = await import(\"c12\");\n```\n\nLoad configuration:\n\n```js\n// Get loaded config\nconst { config } = await loadConfig({});\n\n// Get resolved config and extended layers\nconst { config, configFile, layers } = await loadConfig({});\n```\n\n## Loading priority\n\nc12 merged config sources with [unjs/defu](https://github.com/unjs/defu) by below order:\n\n1. Config overrides passed by options\n2. Config file in CWD\n3. RC file in CWD\n4. Global RC file in the user's home directory\n5. Config from `package.json`\n6. Default config passed by options\n7. Extended config layers\n\n## Options\n\n### `cwd`\n\nResolve configuration from this working directory. The default is `process.cwd()`\n\n### `name`\n\nConfiguration base name. The default is `config`.\n\n### `configFile`\n\nConfiguration file name without extension. Default is generated from `name` (f.e., if `name` is `foo`, the config file will be =\u003e `foo.config`).\n\n### `rcFile`\n\nRC Config file name. Default is generated from `name` (name=foo =\u003e `.foorc`).\n\nSet to `false` to disable loading RC config.\n\n### `globalRc`\n\nLoad RC config from the workspace directory and the user's home directory. Only enabled when `rcFile` is provided. Set to `false` to disable this functionality.\n\n### `dotenv`\n\nLoads `.env` file when `true` or an options object is passed. It is disabled by default.\n\nSupports loading multiple files that extend eachother in left-to-right order when a `fileName`s array of relative/absolute paths is passed in the options object.\n\n**Example:**\n\n```ini\n# .env\nCONNECTION_POOL_MAX=\"10\"\nDATABASE_URL=\"\u003c...rds...\u003e\"\n```\n\n```ini\n# .env.local\nDATABASE_URL=\"\u003c...localhost...\u003e\"\n```\n\n```js\nexport default {\n  connectionPoolMax: process.env.CONNECTION_POOL_MAX,\n  databaseURL: process.env.DATABASE_URL,\n};\n```\n\n```ts\nimport { loadConfig } from \"c12\";\n\nconst config = await loadConfig({\n  dotenv: {\n    fileName: [\".env\", \".env.local\"],\n  },\n});\n\nconsole.log(config.config.connectionPoolMax); // \"10\"\nconsole.log(config.config.databaseURL); // \"\u003c...localhost...\u003e\"\n```\n\n#### `expandFileReferences`\n\nEnabled by default. Environment variables ending with `_FILE` are resolved by reading the file at the specified path and assigning its trimmed content to the base key (without the `_FILE` suffix). This is useful for container secrets (e.g. Docker, Kubernetes) where sensitive values are mounted as files. Set to `false` to disable.\n\n```ini\n# .env\nDATABASE_PASSWORD_FILE=\"/run/secrets/db_password\"\n```\n\n```ts\nimport { loadConfig } from \"c12\";\n\nconst config = await loadConfig({\n  dotenv: true,\n});\n\n// DATABASE_PASSWORD is now set to the contents of /run/secrets/db_password\n```\n\n### `packageJson`\n\nLoads config from nearest `package.json` file. It is disabled by default.\n\nIf `true` value is passed, c12 uses `name` field from `package.json`.\n\nYou can also pass either a string or an array of strings as a value to use those fields.\n\n### `defaults`\n\nSpecify default configuration. It has the **lowest** priority and is applied **after extending** config.\n\n### `defaultConfig`\n\nSpecify default configuration. It is applied **before** extending config.\n\n### `overrides`\n\nSpecify override configuration. It has the **highest** priority and is applied **before extending** config.\n\n### `omit$Keys`\n\nExclude environment-specific and built-in keys start with `$` in the resolved config. The default is `false`.\n\n### `import`\n\nCustom import function used to load configuration files. By default, c12 uses native `import()` with [unjs/jiti](https://github.com/unjs/jiti) as fallback.\n\n**Example:** Using a custom [jiti](https://github.com/unjs/jiti) instance with options:\n\n```js\nimport { createJiti } from \"jiti\";\n\nconst jiti = createJiti(import.meta.url, {\n  /* jiti options */\n});\n\nconst { config } = await loadConfig({\n  import: (id) =\u003e jiti.import(id),\n});\n```\n\n### `resolveModule`\n\nCustom resolver for picking which export to use from the loaded module. Default: `(mod) =\u003e mod.default || mod`.\n\n**Example:** Using a named export:\n\n```js\nconst { config } = await loadConfig({\n  resolveModule: (mod) =\u003e mod.myConfig,\n});\n```\n\n### `giget`\n\nOptions passed to [unjs/giget](https://github.com/unjs/giget) when extending layer from git source.\n\n### `merger`\n\nCustom options merger function. Default is [defu](https://github.com/unjs/defu).\n\n**Note:** Custom merge function should deeply merge options with arguments high -\u003e low priority.\n\n### `envName`\n\nEnvironment name used for [environment specific configuration](#environment-specific-configuration).\n\nThe default is `process.env.NODE_ENV`. You can set `envName` to `false` or an empty string to disable the feature.\n\n### `context`\n\nContext object passed to dynamic config functions.\n\n### `resolve`\n\nYou can define a custom function that resolves the config.\n\n### `configFileRequired`\n\nIf this option is set to `true`, loader fails if the main config file does not exists.\n\n## Extending configuration\n\nIf resolved config contains a `extends` key, it will be used to extend the configuration.\n\nExtending can be nested and each layer can extend from one base or more.\n\nThe final config is merged result of extended options and user options with [unjs/defu](https://github.com/unjs/defu).\n\nEach item in extends is a string that can be either an absolute or relative path to the current config file pointing to a config file for extending or the directory containing the config file.\nIf it starts with either `github:`, `gitlab:`, `bitbucket:`, or `https:`, c12 automatically clones it.\n\nFor custom merging strategies, you can directly access each layer with `layers` property.\n\n**Example:**\n\n```js\n// config.ts\nexport default {\n  colors: {\n    primary: \"user_primary\",\n  },\n  extends: [\"./theme\"],\n};\n```\n\n```js\n// config.dev.ts\nexport default {\n  dev: true,\n};\n```\n\n```js\n// theme/config.ts\nexport default {\n  extends: \"../base\",\n  colors: {\n    primary: \"theme_primary\",\n    secondary: \"theme_secondary\",\n  },\n};\n```\n\n```js\n// base/config.ts\nexport default {\n  colors: {\n    primary: \"base_primary\",\n    text: \"base_text\",\n  },\n};\n```\n\nThe loaded configuration would look like this:\n\n```js\nconst config = {\n  dev: true,\n  colors: {\n    primary: \"user_primary\",\n    secondary: \"theme_secondary\",\n    text: \"base_text\",\n  },\n};\n```\n\nLayers:\n\n```js\n[\n  {\n    config: {\n      /* theme config */\n    },\n    configFile: \"/path/to/theme/config.ts\",\n    cwd: \"/path/to/theme \",\n  },\n  {\n    config: {\n      /* base  config */\n    },\n    configFile: \"/path/to/base/config.ts\",\n    cwd: \"/path/to/base\",\n  },\n  {\n    config: {\n      /* dev   config */\n    },\n    configFile: \"/path/to/config.dev.ts\",\n    cwd: \"/path/\",\n  },\n];\n```\n\n## Extending config layer from remote sources\n\n\u003e [!NOTE]\n\u003e Extending from remote sources requires the [`giget`](https://giget.unjs.io) peer dependency to be installed.\n\u003e\n\u003e ```sh\n\u003e # ✨ Auto-detect\n\u003e npx nypm install giget\n\u003e ```\n\nYou can also extend configuration from remote sources such as npm or github.\n\nIn the repo, there should be a `config.ts` (or `config.{name}.ts`) file to be considered as a valid config layer.\n\n**Example:** Extend from a github repository\n\n```js\n// config.ts\nexport default {\n  extends: \"gh:user/repo\",\n};\n```\n\n**Example:** Extend from a github repository with branch and subpath\n\n```js\n// config.ts\nexport default {\n  extends: \"gh:user/repo/theme#dev\",\n};\n```\n\n**Example:** Extend a private repository and install dependencies:\n\n```js\n// config.ts\nexport default {\n  extends: [\"gh:user/repo\", { auth: process.env.GITHUB_TOKEN, install: true }],\n};\n```\n\nYou can pass more options to `giget: {}` in layer config or disable it by setting it to `false`.\n\nRefer to [unjs/giget](https://giget.unjs.io) for more information.\n\n## Environment-specific configuration\n\nUsers can define environment-specific configuration using these config keys:\n\n- `$test: {...}`\n- `$development: {...}`\n- `$production: {...}`\n- `$env: { [env]: {...} }`\n\nc12 tries to match [`envName`](#envname) and override environment config if specified.\n\n**Note:** Environment will be applied when extending each configuration layer. This way layers can provide environment-specific configuration.\n\n**Example:**\n\n```js\nexport default {\n  // Default configuration\n  logLevel: \"info\",\n\n  // Environment overrides\n  $test: { logLevel: \"silent\" },\n  $development: { logLevel: \"warning\" },\n  $production: { logLevel: \"error\" },\n  $env: {\n    staging: { logLevel: \"debug\" },\n  },\n};\n```\n\n## Watching configuration\n\nyou can use `watchConfig` instead of `loadConfig` to load config and watch for changes, add and removals in all expected configuration paths and auto reload with new config.\n\n\u003e [!NOTE]\n\u003e Watching requires the [`chokidar`](https://github.com/paulmillr/chokidar) peer dependency to be installed.\n\u003e\n\u003e ```sh\n\u003e # ✨ Auto-detect\n\u003e npx nypm install chokidar\n\u003e ```\n\n### Lifecycle hooks\n\n- `onWatch`: This function is always called when config is updated, added, or removed before attempting to reload the config.\n- `acceptHMR`: By implementing this function, you can compare old and new functions and return `true` if a full reload is not needed.\n- `onUpdate`: This function is always called after the new config is updated. If `acceptHMR` returns true, it will be skipped.\n\n```ts\nimport { watchConfig } from \"c12\";\n\nconst config = watchConfig({\n  cwd: \".\",\n  // chokidarOptions: {}, // Default is { ignoreInitial: true }\n  // debounce: 200 // Default is 100. You can set it to false to disable debounced watcher\n  onWatch: (event) =\u003e {\n    console.log(\"[watcher]\", event.type, event.path);\n  },\n  acceptHMR({ oldConfig, newConfig, getDiff }) {\n    const diff = getDiff();\n    if (diff.length === 0) {\n      console.log(\"No config changed detected!\");\n      return true; // No changes!\n    }\n  },\n  onUpdate({ oldConfig, newConfig, getDiff }) {\n    const diff = getDiff();\n    console.log(\"Config updated:\\n\" + diff.map((i) =\u003e i.toJSON()).join(\"\\n\"));\n  },\n});\n\nconsole.log(\"watching config files:\", config.watchingFiles);\nconsole.log(\"initial config\", config.config);\n\n// Stop watcher when not needed anymore\n// await config.unwatch();\n```\n\n## Updating config\n\n\u003e [!NOTE]\n\u003e This feature is experimental\n\nUpdate or create a new configuration files.\n\nAdd `magicast` peer dependency:\n\n```sh\n# ✨ Auto-detect\nnpx nypm install -D magicast\n```\n\nImport util from `c12/update`\n\n```js\nconst { configFile, created } = await updateConfig({\n  cwd: \".\",\n  configFile: \"foo.config\",\n  onCreate: ({ configFile }) =\u003e {\n    // You can prompt user if wants to create a new config file and return false to cancel\n    console.log(`Creating new config file in ${configFile}...`);\n    return \"export default { test: true }\";\n  },\n  onUpdate: (config) =\u003e {\n    // You can update the config contents just like an object\n    config.test2 = false;\n  },\n});\n\nconsole.log(`Config file ${created ? \"created\" : \"updated\"} in ${configFile}`);\n```\n\n## Configuration functions\n\nYou can use a function to define your configuration dynamically based on context.\n\n```ts\n// config.ts\nexport default (ctx) =\u003e {\n  return {\n    apiUrl: ctx?.dev ? \"http://localhost:3000\" : \"https://api.example.com\",\n  };\n};\n```\n\n```ts\n// Usage\nimport { loadConfig } from \"c12\";\n\nconst config = await loadConfig({\n  context: { dev: true },\n});\n```\n\n## Contribution\n\n\u003cdetails\u003e\n  \u003csummary\u003eLocal development\u003c/summary\u003e\n\n- Clone this repository\n- Install the latest LTS version of [Node.js](https://nodejs.org/en/)\n- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable`\n- Install dependencies using `pnpm install`\n- Run tests using `pnpm dev` or `pnpm test`\n\n\u003c/details\u003e\n\n\u003c!-- /automd --\u003e\n\n## License\n\n\u003c!-- automd:contributors license=MIT author=\"pi0\" --\u003e\n\nPublished under the [MIT](https://github.com/unjs/c12/blob/main/LICENSE) license.\nMade by [@pi0](https://github.com/pi0) and [community](https://github.com/unjs/c12/graphs/contributors) 💛\n\u003cbr\u003e\u003cbr\u003e\n\u003ca href=\"https://github.com/unjs/c12/graphs/contributors\"\u003e\n\u003cimg src=\"https://contrib.rocks/image?repo=unjs/c12\" /\u003e\n\u003c/a\u003e\n\n\u003c!-- /automd --\u003e\n\n\u003c!-- automd:with-automd --\u003e\n\n---\n\n_🤖 auto updated with [automd](https://automd.unjs.io)_\n\n\u003c!-- /automd --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Funjs%2Fc12","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Funjs%2Fc12","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Funjs%2Fc12/lists"}