Socket
Socket
Sign inDemoInstall

c12

Package Overview
Dependencies
8
Maintainers
1
Versions
40
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

c12


Version published
Weekly downloads
682K
increased by1.72%
Maintainers
1
Created
Weekly downloads
 

Package description

What is c12?

The c12 npm package is a configuration loader and manager that helps in loading, merging, and managing configurations from various sources such as files, environment variables, and more. It is designed to be flexible and easy to use, making it suitable for a wide range of applications.

What are c12's main functionalities?

Loading Configuration from Files

This feature allows you to load configuration from files. The `loadConfig` function reads configuration files based on the provided options such as the name of the application and the current working directory.

const { loadConfig } = require('c12');

async function loadConfigExample() {
  const config = await loadConfig({
    name: 'myapp',
    cwd: process.cwd(),
    rcFile: true
  });
  console.log(config);
}

loadConfigExample();

Merging Configurations

This feature allows you to merge configurations from different sources. The `loadConfig` function can take default configurations and override configurations, merging them into a single configuration object.

const { loadConfig } = require('c12');

async function mergeConfigExample() {
  const config = await loadConfig({
    name: 'myapp',
    defaults: { key1: 'default1' },
    overrides: { key2: 'override2' }
  });
  console.log(config);
}

mergeConfigExample();

Loading Configuration from Environment Variables

This feature allows you to load configuration from environment variables. The `loadConfig` function can be configured to read environment variables with a specific prefix and include them in the configuration object.

const { loadConfig } = require('c12');

async function envConfigExample() {
  process.env.MYAPP_KEY = 'valueFromEnv';
  const config = await loadConfig({
    name: 'myapp',
    envPrefix: 'MYAPP_'
  });
  console.log(config);
}

envConfigExample();

Other packages similar to c12

Changelog

Source

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

Readme

Source

c12

npm version npm downloads Github Actions Codecov

Smart Configuration Loader

Features

  • JSON, CJS, Typescript, and ESM config loader with unjs/jiti
  • RC config support with unjs/rc9
  • Multiple sources merged with unjs/defu
  • .env support with dotenv
  • Support reading config from the nearest package.json file
  • Support extending nested configurations from multiple local or git sources

Usage

Install package:

# npm
npm install c12

# yarn
yarn add c12

# pnpm
pnpm install c12

Import:

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

// CommonJS
const { loadConfig } = require("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 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.

configName

Configuration file name without extension. Default is generated from name (name=foo => foo.config).

Set to false to avoid loading the config file.

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.

jiti

Custom unjs/jiti instance used to import configuration files.

jitiOptions

Custom unjs/jiti options to import configuration files.

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.

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:

{
  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/ */ },
]

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:

{
  // Default configuration
  logLevel: 'info',

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

💻 Development

  • Clone this repository
  • Enable Corepack using corepack enable (use npm i -g corepack for Node.js < 16.10)
  • Install dependencies using pnpm install
  • Run interactive tests using pnpm dev

License

Made with 💛 Published under MIT License.

FAQs

Last updated on 13 Mar 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc