CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-cosmiconfig

Find and load configuration from a package.json property, rc file, TypeScript module, and more!

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

loaders.mddocs/

File Loaders

Cosmiconfig provides built-in loaders for common configuration file formats and supports custom loaders for specialized needs.

Capabilities

Built-in Loaders

loadJson()

Parses JSON content with enhanced error handling.

/**
 * Parse JSON content with enhanced error handling
 * @param filepath - Path to the JSON file (used for error messages)
 * @param content - Raw JSON content string
 * @returns Parsed JSON object or null if parsing fails
 */
function loadJson(filepath: string, content: string): LoaderResult;

Usage Examples:

// loadJson is used internally by cosmiconfig and is not directly importable
// It is used when processing .json files through the default loaders
const explorer = cosmiconfig("myapp");
const result = await explorer.load("./config.json");
if (result) {
  console.log(result.config); // { key: "value" }
}

loadYaml()

Parses YAML content with error handling.

/**
 * Parse YAML content with error handling
 * @param filepath - Path to the YAML file (used for error messages)
 * @param content - Raw YAML content string
 * @returns Parsed YAML object or null if parsing fails
 */
function loadYaml(filepath: string, content: string): LoaderResult;

Usage Examples:

// loadYaml is used internally by cosmiconfig and is not directly importable
// It is used when processing .yaml/.yml files through the default loaders
const explorer = cosmiconfig("myapp");
const result = await explorer.load("./config.yaml");
if (result) {
  console.log(result.config.settings.debug); // true
}

loadJs()

Loads JavaScript modules asynchronously using dynamic imports.

/**
 * Load JavaScript modules asynchronously using dynamic imports
 * @param filepath - Path to the JavaScript file
 * @param content - Raw JavaScript content (unused in current implementation)
 * @returns Promise resolving to module's default export or the module itself
 */
function loadJs(filepath: string, content: string): Promise<LoaderResult>;

loadJsSync()

Loads JavaScript modules synchronously using require().

/**
 * Load JavaScript modules synchronously using require()
 * @param filepath - Path to the JavaScript file
 * @param content - Raw JavaScript content (unused in current implementation)
 * @returns Module's exported value
 */
function loadJsSync(filepath: string, content: string): LoaderResult;

Usage Examples:

// loadJs and loadJsSync are used internally by cosmiconfig and are not directly importable
// They are used when processing .js/.mjs/.cjs files through the default loaders
const explorer = cosmiconfig("myapp");
const explorerSync = cosmiconfigSync("myapp");

// Async loading
const asyncResult = await explorer.load("./config.js");

// Sync loading  
const syncResult = explorerSync.load("./config.js");

loadTs()

Transpiles and loads TypeScript modules asynchronously.

/**
 * Transpile and load TypeScript modules asynchronously
 * @param filepath - Path to the TypeScript file
 * @param content - Raw TypeScript content string
 * @returns Promise resolving to transpiled and executed module
 */
function loadTs(filepath: string, content: string): Promise<LoaderResult>;

loadTsSync()

Transpiles and loads TypeScript modules synchronously.

/**
 * Transpile and load TypeScript modules synchronously
 * @param filepath - Path to the TypeScript file
 * @param content - Raw TypeScript content string
 * @returns Transpiled and executed module
 */
function loadTsSync(filepath: string, content: string): LoaderResult;

Usage Examples:

// loadTs and loadTsSync are used internally by cosmiconfig and are not directly importable
// They are used when processing .ts files through the default loaders
const explorer = cosmiconfig("myapp");
const explorerSync = cosmiconfigSync("myapp");

// Async loading of TypeScript config
const asyncResult = await explorer.load("./config.ts");  

// Sync loading of TypeScript config
const syncResult = explorerSync.load("./config.ts");

Default Loader Maps

defaultLoaders

Default async loaders for different file extensions.

const defaultLoaders: Readonly<{
  '.mjs': typeof loadJs;
  '.cjs': typeof loadJs;
  '.js': typeof loadJs;
  '.ts': typeof loadTs;
  '.json': typeof loadJson;
  '.yaml': typeof loadYaml;
  '.yml': typeof loadYaml;
  noExt: typeof loadYaml;
}>;

defaultLoadersSync

Default sync loaders (excludes .mjs since ES modules can't be loaded synchronously).

const defaultLoadersSync: Readonly<{
  '.cjs': typeof loadJsSync;
  '.js': typeof loadJsSync;
  '.ts': typeof loadTsSync;
  '.json': typeof loadJson;
  '.yaml': typeof loadYaml;
  '.yml': typeof loadYaml;
  noExt: typeof loadYaml;
}>;

Usage Examples:

import { cosmiconfig, defaultLoaders, defaultLoadersSync } from "cosmiconfig";

// Use default loaders as basis for custom loaders
const customLoaders = {
  ...defaultLoaders,
  '.toml': customTomlLoader
};

const explorer = cosmiconfig("myapp", {
  loaders: customLoaders
});

Custom Loaders

You can define custom loaders for specialized file formats:

type Loader = (filepath: string, content: string) => Promise<LoaderResult> | LoaderResult;
type LoaderSync = (filepath: string, content: string) => LoaderResult;
type LoaderResult = any | null;

interface Loaders {
  [extension: string]: Loader;
}

interface LoadersSync {
  [extension: string]: LoaderSync;
}

Custom Loader Examples:

import { cosmiconfig } from "cosmiconfig";

// Custom TOML loader
const tomlLoader = (filepath: string, content: string) => {
  const TOML = require("@iarna/toml");
  try {
    return TOML.parse(content);
  } catch (error) {
    error.message = `TOML Error in ${filepath}: ${error.message}`;
    throw error;
  }
};

// Custom INI loader
const iniLoader = (filepath: string, content: string) => {
  const ini = require("ini");
  return ini.parse(content);
};

// Use custom loaders
const explorer = cosmiconfig("myapp", {
  loaders: {
    '.toml': tomlLoader,
    '.ini': iniLoader,
    noExt: tomlLoader // Use TOML for extensionless files
  }
});

Loader Error Handling

Loaders should handle errors gracefully and provide useful error messages:

// Good loader error handling pattern
const customLoader = (filepath: string, content: string): LoaderResult => {
  try {
    return parseCustomFormat(content);
  } catch (error) {
    // Enhance error with file path information
    error.message = `Error parsing ${filepath}: ${error.message}`;
    throw error;
  }
};

Meta Search Places

Default search locations for meta configuration:

const metaSearchPlaces: readonly string[] = [
  'package.json',
  '.config.json',
  '.config.yaml',
  '.config.yml',
  '.config.js',
  '.config.ts',
  '.config.cjs',
  '.config.mjs'
];

These are used internally for searching meta-configuration that might specify where to find the actual configuration files.

docs

configuration.md

core-api.md

index.md

loaders.md

tile.json