How to use the cosmiconfigSync function from cosmiconfig

Find comprehensive JavaScript cosmiconfig.cosmiconfigSync code examples handpicked from public code repositorys.

cosmiconfig.cosmiconfigSync is a synchronous version of the cosmiconfig package, which allows you to search for and load configuration files based on a given name and options.

97
98
99
100
101
102
103
104
105
106

function loadYaml(filepath, content) {
    return defaultLoaders['.yaml'](filepath, stripBom(content));
}

const explorerSync = cosmiconfigSync(MODULE_NAME, {
    cache: false,
    loaders: {
        '.json': loadJson,
        '.yaml': loadYaml,
fork icon0
star icon2
watch icon0

200
201
202
203
204
205
206
207
208

### cosmiconfigSync()

```js
const { cosmiconfigSync } = require('cosmiconfig');
const explorerSync = cosmiconfigSync(moduleName[, cosmiconfigOptions])
```

Creates a *synchronous* cosmiconfig instance ("explorerSync") configured according to the arguments, and initializes its caches.
fork icon160
star icon1
watch icon1

+ 5 other calls in file

How does cosmiconfig.cosmiconfigSync work?

cosmiconfig.cosmiconfigSync works by searching for and loading configuration files based on a given name and options in a synchronous manner. When you call cosmiconfigSync, you pass it a moduleName and an optional options object. The moduleName is the name of the configuration file to search for, such as eslintrc, babelrc, or prettierrc. The options object can contain properties that affect how the search and loading process is performed, such as the stopDir property, which specifies the directory where the search should stop. cosmiconfigSync first looks for a configuration file with the given name in the current working directory. If a configuration file is not found in the current directory, cosmiconfigSync will recursively search up the directory tree until a configuration file is found or the stopDir option is reached. Once a configuration file is found, cosmiconfigSync loads and parses the file and returns an object with the configuration data. If no configuration file is found, cosmiconfigSync returns null. cosmiconfigSync is a synchronous function, which means that it will block the main thread until the search and loading process is complete. This can be useful in situations where you need to load configuration data synchronously, such as when initializing a module or application. However, it can also cause performance issues if used improperly.

114
115
116
117
118
119
120
121
122
123
124
125
const resolveConfig = (path) => {
  if (path && resolvedConfigs[path]) {
    return resolvedConfigs[path];
  }


  const explorerSync = cosmiconfigSync('sfdev');
  const result = explorerSync.search(path);


  if (!path && result) {
    path = dirname(result.filepath);
fork icon2
star icon4
watch icon10

+ 8 other calls in file

15
16
17
18
19
20
21
22
23
24
25
26


exports.getConfigs = async function getConfigs() {
  const { argv } = yargs(hideBin(process.argv))
  const cliConfig = argv instanceof Promise ? await argv : argv
  const configPath = cliConfig['config'] || cliConfig['c']
  const fileConfig = typeof configPath === 'string' ? require(resolve(process.cwd(), configPath)) : cosmiconfigSync('jest').search(join(__dirname, '..'))?.config ?? {}


  const result = [
    ['transform', `{"^.+\\\\.tsx?$":"${await getTsJestPath()}"}`],
    ['passWithNoTests'],
fork icon0
star icon0
watch icon1

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
const { cosmiconfigSync } = require("cosmiconfig");

const result = cosmiconfigSync("myconfig").search();

if (result) {
  console.log(`Configuration file found at ${result.filepath}:`);
  console.log(result.config);
} else {
  console.log("No configuration file found.");
}

In this example, we import the cosmiconfigSync function from the cosmiconfig package. We then call cosmiconfigSync with the name of the configuration file to search for, which in this case is 'myconfig'. We then call the search method on the result of the cosmiconfigSync function, which performs the search and loading process and returns an object with the configuration data if a configuration file is found. If a configuration file is found, we log a message to the console that includes the filepath where the configuration file was found, as well as the configuration data itself. If a configuration file is not found, we log a message to the console indicating that no configuration file was found. Note that cosmiconfigSync is a synchronous function, so it will block the main thread until the search and loading process is complete. This can cause performance issues if used improperly, so it's generally recommended to use the asynchronous version of the cosmiconfig package (cosmiconfig.cosmiconfig) whenever possible.

61
62
63
64
65
66
67
68
69
70
  config = null,
  onComplete: wpOnComplete = null,
} = this.options;

let loadedConfig = null;
const explorerSync = cosmiconfigSync('fantasticon', {
  searchPlaces: searchPlaces('fantasticon'),
});
if (configPath) {
  loadedConfig = explorerSync.load(configPath);
fork icon0
star icon0
watch icon0

+ 3 other calls in file

0
1
2
3
4
5
6
7
8
9
10
11
12
const { cosmiconfigSync } = require('cosmiconfig');
const { get, mapValues, isEmpty } = require('lodash');


const { writeObjectToDestModuleJSFileSync } = require('./fs');


const explorerSync = cosmiconfigSync('configs');


const readSync = () => {
  const res = explorerSync.search();
  return get(res, 'config', null);
fork icon0
star icon0
watch icon0

+ 3 other calls in file

54
55
56
57
58
59
60
61
62
63
]

const {cosmiconfigSync} = require('cosmiconfig')

// Match config files based on the specificity from most to most general.
const explorerSync = cosmiconfigSync(targetName, {
    packageProp: 'mobify',
    searchPlaces: searchPlaces,
    loaders: {
        '.js': (filepath) => {
fork icon0
star icon0
watch icon0

+ 3 other calls in file

27
28
29
30
31
32
33
34
35
36
}
const contents = fs.readFileSync(input, "utf8")
// 2, 使用marked 将md文件转换成html
const fragment = marked(contents)
// 加载配置文件中的模版 配置文件名称 .md2pngrc
const explorer = cosmiconfigSync("md2png")
const { config = {} } = explorer.search(process.cwd()) || {}
// 为markdown添加样式
const html = config.template.replace("${fragment}", fragment)
const width = Number(options.width || 800)
fork icon0
star icon0
watch icon0

45
46
47
48
49
50
51
52
53
54

/**
 * @param {string} [cwd] Defaults to process.cwd()
 */
constructor(cwd) {
  const explorer = cosmiconfigSync("lerna", {
    searchPlaces: ["lerna.json", "package.json"],
    transform(obj) {
      // cosmiconfig returns null when nothing is found
      if (!obj) {
fork icon0
star icon0
watch icon0

21
22
23
24
25
26
27
28
29
30
const tapAfterEnvironmentToPatchWatching_1 = require("./hooks/tapAfterEnvironmentToPatchWatching");
const pool_1 = require("./utils/async/pool");
const os_1 = __importDefault(require("os"));
class ForkTsCheckerWebpackPlugin {
    constructor(options = {}) {
        const explorerSync = cosmiconfig_1.cosmiconfigSync('fork-ts-checker');
        const { config: externalOptions } = explorerSync.search() || {};
        // first validate options directly passed to the constructor
        const configuration = { name: 'ForkTsCheckerWebpackPlugin' };
        schema_utils_1.default(ForkTsCheckerWebpackPluginOptions_json_1.default, options, configuration);
fork icon0
star icon0
watch icon0

41
42
43
44
45
46
47
48
49
50
51
52
  });
}
console.log(`commander`, commander);
const filenames = glob.sync(commander.args[0]);


const exportSync = cosmiconfigSync("myBabel");
const searchResultconfig = exportSync.search();


console.log(`searchResultconfig===>`, searchResultconfig);
const options = {
fork icon0
star icon0
watch icon0