Package detail

c12

unjs7.7mMIT3.0.3

Smart Config Loader

readme

⚙️ c12

npm version npm downloads codecov

c12 (pronounced as /siːtwelv/, like c-twelve) is a smart configuration loader.

✅ Features

🦴 Used by

Usage

Install package:

# ✨ Auto-detect
npx nypm install c12

# npm
npm install c12

# yarn
yarn add c12

# pnpm
pnpm install c12

# bun
bun install c12

# deno
deno install c12

Import:

// ESM import
import { loadConfig, watchConfig } from "c12";

// or using dynamic import
const { loadConfig, watchConfig } = await import("c12");

Load configuration:

// Get loaded config
const { config } = await loadConfig({});

// Get resolved config and extended layers
const { config, configFile, layers } = await loadConfig({});

Loading priority

c12 merged config sources with unjs/defu by below order:

  1. Config overrides passed by options
  2. Config file in CWD
  3. RC file in CWD
  4. Global RC file in the user's home directory
  5. Config from package.json
  6. Default config passed by options
  7. Extended config layers

Options

cwd

Resolve configuration from this working directory. The default is process.cwd()

name

Configuration base name. The default is config.

configFile

Configuration file name without extension. Default is generated from name (f.e., if name is foo, the config file will be => foo.config).

rcFile

RC Config file name. Default is generated from name (name=foo => .foorc).

Set to false to disable loading RC config.

globalRC

Load 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.

dotenv

Loads .env file if enabled. It is disabled by default.

packageJson

Loads config from nearest package.json file. It is disabled by default.

If true value is passed, c12 uses name field from package.json.

You can also pass either a string or an array of strings as a value to use those fields.

defaults

Specify default configuration. It has the lowest priority and is applied after extending config.

defaultConfig

Specify default configuration. It is applied before extending config.

overrides

Specify override configuration. It has the highest priority and is applied before extending config.

omit$Keys

Exclude environment-specific and built-in keys start with $ in the resolved config. The default is false.

jiti

Custom unjs/jiti instance used to import configuration files.

jitiOptions

Custom unjs/jiti options to import configuration files.

giget

Options passed to unjs/giget when extending layer from git source.

merger

Custom options merger function. Default is defu.

Note: Custom merge function should deeply merge options with arguments high -> low priority.

envName

Environment name used for environment specific configuration.

The default is process.env.NODE_ENV. You can set envName to false or an empty string to disable the feature.

resolve

You can define a custom function that resolves the config.

Extending configuration

If resolved config contains a extends key, it will be used to extend the configuration.

Extending can be nested and each layer can extend from one base or more.

The final config is merged result of extended options and user options with unjs/defu.

Each 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. If it starts with either github:, gitlab:, bitbucket:, or https:, c12 automatically clones it.

For custom merging strategies, you can directly access each layer with layers property.

Example:

// config.ts
export default {
  colors: {
    primary: "user_primary",
  },
  extends: ["./theme"],
};
// config.dev.ts
export default {
  dev: true,
};
// theme/config.ts
export default {
  extends: "../base",
  colors: {
    primary: "theme_primary",
    secondary: "theme_secondary",
  },
};
// base/config.ts
export default {
  colors: {
    primary: "base_primary",
    text: "base_text",
  },
};

The loaded configuration would look like this:

const config = {
  dev: true,
  colors: {
    primary: "user_primary",
    secondary: "theme_secondary",
    text: "base_text",
  },
};

Layers:

[
  {
    config: {
      /* theme config */
    },
    configFile: "/path/to/theme/config.ts",
    cwd: "/path/to/theme ",
  },
  {
    config: {
      /* base  config */
    },
    configFile: "/path/to/base/config.ts",
    cwd: "/path/to/base",
  },
  {
    config: {
      /* dev   config */
    },
    configFile: "/path/to/config.dev.ts",
    cwd: "/path/",
  },
];

Extending config layer from remote sources

You can also extend configuration from remote sources such as npm or github.

In the repo, there should be a config.ts (or config.{name}.ts) file to be considered as a valid config layer.

Example: Extend from a github repository

// config.ts
export default {
  extends: "gh:user/repo",
};

Example: Extend from a github repository with branch and subpath

// config.ts
export default {
  extends: "gh:user/repo/theme#dev",
};

Example: Extend a private repository and install dependencies:

// config.ts
export default {
  extends: ["gh:user/repo", { auth: process.env.GITHUB_TOKEN, install: true }],
};

You can pass more options to giget: {} in layer config or disable it by setting it to false.

Refer to unjs/giget for more information.

Environment-specific configuration

Users can define environment-specific configuration using these config keys:

  • $test: {...}
  • $development: {...}
  • $production: {...}
  • $env: { [env]: {...} }

c12 tries to match envName and override environment config if specified.

Note: Environment will be applied when extending each configuration layer. This way layers can provide environment-specific configuration.

Example:

export default {
  // Default configuration
  logLevel: "info",

  // Environment overrides
  $test: { logLevel: "silent" },
  $development: { logLevel: "warning" },
  $production: { logLevel: "error" },
  $env: {
    staging: { logLevel: "debug" },
  },
};

Watching configuration

you 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.

Lifecycle hooks

  • onWatch: This function is always called when config is updated, added, or removed before attempting to reload the config.
  • acceptHMR: By implementing this function, you can compare old and new functions and return true if a full reload is not needed.
  • onUpdate: This function is always called after the new config is updated. If acceptHMR returns true, it will be skipped.
import { watchConfig } from "c12";

const config = watchConfig({
  cwd: ".",
  // chokidarOptions: {}, // Default is { ignoreInitial: true }
  // debounce: 200 // Default is 100. You can set it to false to disable debounced watcher
  onWatch: (event) => {
    console.log("[watcher]", event.type, event.path);
  },
  acceptHMR({ oldConfig, newConfig, getDiff }) {
    const diff = getDiff();
    if (diff.length === 0) {
      console.log("No config changed detected!");
      return true; // No changes!
    }
  },
  onUpdate({ oldConfig, newConfig, getDiff }) {
    const diff = getDiff();
    console.log("Config updated:\n" + diff.map((i) => i.toJSON()).join("\n"));
  },
});

console.log("watching config files:", config.watchingFiles);
console.log("initial config", config.config);

// Stop watcher when not needed anymore
// await config.unwatch();

Updating config

[!NOTE] This feature is experimental

Update or create a new configuration files.

Add magicast peer dependency:

# ✨ Auto-detect
npx nypm install -D magicast

# npm
npm install -D magicast

# yarn
yarn add -D magicast

# pnpm
pnpm install -D magicast

# bun
bun install -D magicast

# deno
deno install --dev magicast

Import util from c12/update

const { configFile, created } = await updateConfig({
  cwd: ".",
  configFile: "foo.config",
  onCreate: ({ configFile }) => {
    // You can prompt user if wants to create a new config file and return false to cancel
    console.log(`Creating new config file in ${configFile}...`);
    return "export default { test: true }";
  },
  onUpdate: (config) => {
    // You can update the config contents just like an object
    config.test2 = false;
  },
});

console.log(`Config file ${created ? "created" : "updated"} in ${configFile}`);

Contribution

<summary>Local development</summary> - Clone this repository - Install the latest LTS version of Node.js - Enable Corepack using corepack enable - Install dependencies using pnpm install - Run tests using pnpm dev or pnpm test

License

Published under the MIT license. Made by @pi0 and community 💛


🤖 auto updated with automd

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

v3.0.3

compare changes

🩹 Fixes

  • Check if .env/ is a directory before accessing (#238)
  • Update dotenv assigned env variables on subsequent calls (#243)

📖 Documentation

  • Add resolve option (#240)
  • Remove unsupported configFile: false (#239)

🏡 Chore

✅ Tests

  • Only include src for coverage report (#242)

❤️ Contributors

v3.0.2

compare changes

🏡 Chore

❤️ Contributors

  • Pooya Parsa (@pi0)

v3.0.1

compare changes

🩹 Fixes

  • Fix windows related resolve issues (#235)

❤️ Contributors

  • Pooya Parsa (@pi0)

v3.0.0

compare changes

🩹 Fixes

  • Allow custom giget provider (#207)

💅 Refactors

  • Migrate from mlly to exsolve for module resolution (822af14)
  • Fully migrate to exsolve for module resolution (146899e)

📦 Build

🏡 Chore

⚠️ Breaking Changes

❤️ Contributors

v2.0.4

compare changes

📦 Build

❤️ Contributors

  • Pooya Parsa (@pi0)

v2.0.3

compare changes

💅 Refactors

  • Upgrade to ohash v2 (#230)

📦 Build

🏡 Chore

❤️ Contributors

  • Pooya Parsa (@pi0)

v2.0.2

compare changes

🩹 Fixes

  • Preserve meta for main config (#227)

📖 Documentation

  • Add kysely-ctl to readme (#225)

🏡 Chore

❤️ Contributors

v2.0.1

compare changes

🩹 Fixes

🏡 Chore

❤️ Contributors

  • Pooya Parsa (@pi0)

v2.0.0

compare changes

🏡 Chore

❤️ Contributors

  • Pooya Parsa (@pi0)

v2.0.0-beta.3

compare changes

💅 Refactors

🏡 Chore

❤️ Contributors

  • Pooya Parsa (@pi0)

v2.0.0-beta.2

compare changes

🚀 Enhancements

  • Allow disabling remote extend with giget: false (#181)
  • Support update existing .config/[name].[ext] config (#169)

🩹 Fixes

  • updateConfig: Properly resolve config relative to cwd (#188)

🏡 Chore

❤️ Contributors

v2.0.0-beta.1

compare changes

🚀 Enhancements

  • Upgrade to jiti v2 beta (#172)

🏡 Chore

  • Aadd hey-api to list of users (#171)
  • Update release script for beta (0127b2d)
  • Stricter tsconfig (e930e6b)
  • Update deps (da3595c)

❤️ Contributors

v1.11.1

compare changes

🩹 Fixes

  • update: Await on onUpdate (6b37c98)
  • update: Respect falsy value of onCreate (cc4e991)
  • update: Use relative path to resolve config (8b58b25)

❤️ Contributors

  • Pooya Parsa (@pi0)

v1.11.0

compare changes

🚀 Enhancements

  • Resolvable configs (#159)
  • Custom merger to replace built-in defu (#160)
  • Config update util (#162)

🩹 Fixes

  • loadConfig: config is not nullable (#161)

💅 Refactors

  • Internally use named sources (#158)

🏡 Chore

❤️ Contributors

  • Pooya Parsa (@pi0)

v1.10.0

compare changes

🚀 Enhancements

  • Support auth shortcut for layer config (#142)

🏡 Chore

❤️ Contributors

  • Pooya Parsa (@pi0)

v1.9.0

compare changes

🚀 Enhancements

  • Use confbox (#140)

🔥 Performance

🩹 Fixes

  • Deep merge rc sources with defu (#139)
  • watcher: Watch .config and all supported extensions (94c8181)

❤️ Contributors

v1.8.0

compare changes

🚀 Enhancements

  • Support .config dir (#136)

🩹 Fixes

  • Use default export of json5 for parsing (#135)

🏡 Chore

✅ Tests

❤️ Contributors

v1.7.0

compare changes

🚀 Enhancements

  • .jsonc config support (#132)
  • Json5 support (#133)

❤️ Contributors

  • Pooya Parsa (@pi0)

v1.6.1

compare changes

🩹 Fixes

  • Preserve cloned dir if install option provided (81e2891)

❤️ Contributors

  • Pooya Parsa (@pi0)

v1.6.0

compare changes

🚀 Enhancements

  • Option to omit $ keys from resolved config (#100)
  • Support install for source options (#126)

🩹 Fixes

  • Normalize windows backslash for configFile and source (#48)
  • Clone sub layers into node_modules/.c12 (#125)
  • Handle http:// prefixes with giget as well (6c09735)

📖 Documentation

  • Add package pronunciation (#118)

🏡 Chore

❤️ Contributors

  • Pooya Parsa (@pi0)
  • Lo (@LoTwT)
  • Alex Kozack
  • Nozomu Ikuta

v1.5.1

compare changes

🚀 Enhancements

  • Improve extending github layers (#109)
  • Allow setting giget clone options (#112)

🏡 Chore

✅ Tests

  • Update gh fixture to main (a8b73c2)

🎨 Styles

❤️ Contributors

  • Pooya Parsa (@pi0)

v1.4.2

compare changes

🩹 Fixes

  • Allow extends dir to start with dot (#71)

📖 Documentation

  • Fix typo for configFile (#83)

🏡 Chore

❤️ Contributors

v1.4.1

compare changes

🩹 Fixes

  • watchConfig: Handle custom config names (eedd141)

❤️ Contributors

  • Pooya Parsa (@pi0)

v1.4.0

compare changes

🚀 Enhancements

  • watchConfig utility (#77)
  • watchConfig: Support hmr (#78)

📖 Documentation

  • Fix small grammer issues (5f2b3a1)

❤️ Contributors

  • Pooya Parsa (@pi0)

v1.3.0

compare changes

🚀 Enhancements

  • Generic types support (#64)

🩹 Fixes

  • Use rm instead of rmdir for recursive remove (#69)

🏡 Chore

❤️ Contributors

v1.2.0

compare changes

🚀 Enhancements

  • Load config from package.json (#52)
  • Environment specific configuration (#61)
  • Layer meta and source options (#62)
  • envName config (4a0227d)

🩹 Fixes

  • Allow extending from npm packages with subpath (#54)

📖 Documentation

  • Fix grammer and typos (3e8436c)
  • Don't mention unsupported usage (ea7ac6e)

🏡 Chore

✅ Tests

❤️ Contributors

v1.1.2

compare changes

🏡 Chore

❤️ Contributors

v1.1.1

compare changes

🏡 Chore

🎨 Styles

❤️ Contributors

1.1.0 (2022-12-06)

Features

  • use giget to clone github urls (4c7590a)

Bug Fixes

  • remove tmp dir to clone (020e0b0)

1.0.1 (2022-11-15)

1.0.0 (2022-11-15)

0.2.13 (2022-09-19)

0.2.12 (2022-09-14)

Features

  • defaultConfig to be applied before extending (1c4e898)

0.2.11 (2022-09-06)

Features

  • custom jiti and jitiOptions (bfd1be5)
  • support loading rc from workspace dir in global mode (7365a9c)

Bug Fixes

  • jitiOptions is optional (457a045)
  • validate sources value to be string (#32) (f97c850)

0.2.10 (2022-09-01)

Features

  • allow extending from multiple keys (33cb210), closes #24

0.2.9 (2022-08-04)

Features

  • use native esm resolution where possible (#26) (9744621)

0.2.8 (2022-06-29)

Features

  • try resolving paths as npm package (7c48947)

Bug Fixes

  • warn when extend layers cannot be resolved (f6506e8)

0.2.7 (2022-04-20)

Bug Fixes

  • check resolved config file existence before loading (dda579d)

0.2.6 (2022-04-20)

Bug Fixes

  • only ignore MODULE_NOT_FOUND when message contains configFile (e067a56)

0.2.5 (2022-04-07)

0.2.4 (2022-03-21)

Bug Fixes

0.2.3 (2022-03-18)

Bug Fixes

  • don't strip empty config files (#8) (67bb1ee)

0.2.2 (2022-03-16)

0.2.0 (2022-03-16)

⚠ BREAKING CHANGES

  • preserve all merging sources

Features

  • preserve all merging sources (7a69480)

0.1.4 (2022-03-07)

Bug Fixes

0.1.3 (2022-02-10)

Bug Fixes

  • apply defaults after extending (c86024c)

0.1.2 (2022-02-10)

Features

0.1.1 (2022-01-31)

Features

Bug Fixes

  • escape unsupported chars from tmpdir (fd04922)
  • temp directory initialization (3aaf5db)