How to use cosmiconfig - 10 common examples

To help you get started, we’ve selected a few cosmiconfig examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github linthtml / linthtml / lib / cli / read-config.js View on Github external
module.exports.config_from_path = function(file_path) {
  const config_path = path.join(process.cwd(), file_path);
  let isConfigDirectory = false;
  try {
    let config = null;
    isConfigDirectory = fs.lstatSync(config_path).isDirectory();
    if (isConfigDirectory) {
      config = cosmiconfigSync("linthtml", { stopDir: config_path, packageProp: "linthtmlConfig" }).search(config_path);
    } else {
      config = explorer.load(config_path);
    }
    if (config === null) {
      throw new Error();
    }
    return config;
  } catch (error) {
    if (isConfigDirectory) {
      throw new CustomError("CLI-01", { config_path });
      // console.log(`{red Error:} Cannot read config file in directory: {underline ${config_path}}`);
    }
    throw new CustomError("CLI-02", { config_path });
  }
};
github iopipe / serverless-plugin-iopipe / src / index.js View on Github external
getConfig() {
    const { token } = this.getOptions();
    const { config: cosmi = {} } =
      cosmiconfig('iopipe', {
        cache: false,
        sync: true,
        rcExtensions: true
      }).load(process.cwd()) || {};

    const plugins = (cosmi.plugins || []).map(plugin => {
      // plugins can be specified as strings or as arrays with 2 entries
      // ["@iopipe/trace", ["@iopipe/logger", {"enabled": true}]]
      // create require calls for each scenario
      const pluginModule = _.isArray(plugin) ? plugin[0] : plugin;
      const pluginConfig = _.isArray(plugin) ? JSON.stringify(plugin[1]) : '';
      return `require('${pluginModule}')(${pluginConfig})`;
    });

    const inlineConfigObject = _.pickBy(
      _.assign({}, cosmi, {
github kamilkisiela / graphql-config / src / helpers.ts View on Github external
function createCosmiConfig() {
  // We need to wrap loaders in order to access and transform file content (as string)
  // Cosmiconfig has transform option but at this point config is not a string but an object
  return cosmiconfig('graphql', {
    loaders: {
      '.js': {sync: cosmi.loadJs, async: cosmi.loadJs},
      '.json': loadJson,
      '.yaml': loadYaml,
      '.yml': loadYaml,
      noExt: loadYaml,
    },
  });
}
github Cretezy / Noderize / packages / scripts / src / options.js View on Github external
type => types[type].type === Boolean
  );

  // Parse args
  const args = parseArgs(rawArgs || [], {
    boolean: boleans,
    string: Object.keys(types).filter(
      type => types[type].type === String || types[type].type === Object
    ),
    default: boleans.reduce((total, bool) => ({ ...total, [bool]: null }), {})
  });

  let options = {};
  try {
    // Load from "noderize" key in package.json, .noderizerc, or noderize.config.js
    const results = cosmiconfig("noderize").searchSync();

    if (results) {
      const configOptions = results.config || {};
      Object.keys(configOptions).forEach(configOptionKey => {
        if (types[configOptionKey] !== undefined) {
          const type = types[configOptionKey];
          let value = configOptions[configOptionKey];
          if (type.type === Array && !Array.isArray(value)) {
            value = [value];
          }
          value = run(type.run, value, { options });
          options[configOptionKey] = value;
        } else {
          log.warn(`Config key '${configOptionKey}' doesn't do anything.`);
        }
      });
github CVarisco / create-component-app / src / utils.js View on Github external
function getConfig(configPath, searchPath = process.cwd(), stopDir = homedir()) {
  const useCustomPath = !!configPath
  const explorer = cosmiconfig('cca', { sync: true, stopDir })

  try {
    const searchPathAbsolute = !useCustomPath && searchPath
    const configPathAbsolute = useCustomPath && path.join(process.cwd(), configPath)
    // search from the root of the process if the user didnt specify a config file,
    // or use the custom path if a file is passed.
    const result = explorer.load(searchPathAbsolute, configPathAbsolute)

    // dont throw if the explorer didnt find a configfile,
    // instead use default config
    const config = result ? result.config : {}
    const filepath = result ? result.filepath : {}
    if (!result) Logger.log('No config file detected, using defaults.')

    return { ...config, filepath }
  } catch (error) {
github stylelint / stylelint / src / buildConfig.js View on Github external
function loadExtendedConfig(config, configDir, extendLookup) {
  const extendPath = getModulePath(configDir, extendLookup)
  const extendDir = path.dirname(extendPath)
  return cosmiconfig(null, {
    configPath: extendPath,
    // In case `--config` was used: do not pay attention to it again
    argv: false,
  }).then(result => {
    // Make sure to also augment the config that we're merging in
    // ... but the `ignoreFiles` option only works with the
    // config that is being directly invoked, not any
    // extended configs
    return augmentConfig(stripIgnoreFiles(result.config), extendDir)
  })
}
github kentcdodds / babel-plugin-macros / src / index.js View on Github external
function getConfigExporer() {
  return (_configExplorer =
    _configExplorer ||
    // Lazy load cosmiconfig since it is a relatively large bundle
    require('cosmiconfig').cosmiconfigSync('babel-plugin-macros', {
      searchPlaces: [
        'package.json',
        '.babel-plugin-macrosrc',
        '.babel-plugin-macrosrc.json',
        '.babel-plugin-macrosrc.yaml',
        '.babel-plugin-macrosrc.yml',
        '.babel-plugin-macrosrc.js',
        'babel-plugin-macros.config.js',
      ],
      packageProp: 'babelMacros',
    }))
}
github wintercounter / mhy / src / resources / babelPluginMacros.js View on Github external
function getConfigExporer() {
    return (_configExplorer =
        _configExplorer || // Lazy load cosmiconfig since it is a relatively large bundle
        require('cosmiconfig').cosmiconfigSync('babel-plugin-macros', {
            searchPlaces: [
                'package.json',
                '.babel-plugin-macrosrc',
                '.babel-plugin-macrosrc.json',
                '.babel-plugin-macrosrc.yaml',
                '.babel-plugin-macrosrc.yml',
                '.babel-plugin-macrosrc.js',
                'babel-plugin-macros.config.js'
            ],
            packageProp: 'babelMacros'
        }))
}
github semantic-release / semantic-release / lib / get-config.js View on Github external
module.exports = async (context, opts) => {
  const {cwd, env} = context;
  const {config, filepath} = (await cosmiconfig(CONFIG_NAME, {searchPlaces: CONFIG_FILES}).search(cwd)) || {};

  debug('load config from: %s', filepath);

  // Merge config file options and CLI/API options
  let options = {...config, ...opts};
  if (options.ci === false) {
    options.noCi = true;
  }

  const pluginsPath = {};
  let extendPaths;
  ({extends: extendPaths, ...options} = options);
  if (extendPaths) {
    // If `extends` is defined, load and merge each shareable config with `options`
    options = {
      ...castArray(extendPaths).reduce((result, extendPath) => {
github IBM / report-toolkit / packages / fs / src / fs-config-loader.js View on Github external
const getExplorer = _.memoize(opts =>
  cosmiconfig(
    RC_NAMESPACE,
    _.defaultsDeep(
      {
        // @ts-ignore
        loaders: {noExt: cosmiconfig.loadJs}
      },
      opts
    )
  )
);

cosmiconfig

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

MIT
Latest version published 11 months ago

Package Health Score

83 / 100
Full package analysis