UNPKG

1.46 kBJavaScriptView Raw
1import { lilconfig } from 'lilconfig'
2import YAML from 'yaml'
3
4/**
5 * The list of files `lint-staged` will read configuration
6 * from, in the declared order.
7 */
8const searchPlaces = [
9 'package.json',
10 '.lintstagedrc',
11 '.lintstagedrc.json',
12 '.lintstagedrc.yaml',
13 '.lintstagedrc.yml',
14 '.lintstagedrc.mjs',
15 '.lintstagedrc.js',
16 '.lintstagedrc.cjs',
17 'lint-staged.config.mjs',
18 'lint-staged.config.js',
19 'lint-staged.config.cjs',
20]
21
22/** exported for tests */
23export const dynamicImport = (path) =>
24 import(path)
25 .then((module) => module.default)
26 .catch((error) => {
27 console.error(error)
28 throw error
29 })
30
31const jsonParse = (path, content) => JSON.parse(content)
32
33/**
34 * `lilconfig` doesn't support yaml files by default,
35 * so we add custom loaders for those. Files without
36 * an extensions are assumed to be yaml — this
37 * assumption is in `cosmiconfig` as well.
38 */
39const loaders = {
40 '.js': dynamicImport,
41 '.json': jsonParse,
42 '.mjs': dynamicImport,
43 '.cjs': dynamicImport,
44 '.yaml': YAML.parse,
45 '.yml': YAML.parse,
46 noExt: YAML.parse,
47}
48
49const resolveConfig = (configPath) => {
50 try {
51 return require.resolve(configPath)
52 } catch {
53 return configPath
54 }
55}
56
57/**
58 * @param {string} [configPath]
59 */
60export const loadConfig = (configPath) => {
61 const explorer = lilconfig('lint-staged', { searchPlaces, loaders })
62 return configPath ? explorer.load(resolveConfig(configPath)) : explorer.search()
63}