forked from akameco/read-babelrc-up
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
72 lines (61 loc) · 1.71 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict'
const path = require('path')
const fs = require('fs')
const findUp = require('find-up')
const json5 = require('json5')
// https://babeljs.io/docs/en/config-files#supported-file-extensions
const BABELRC = ['.babelrc', '.babelrc.json', 'babel.config.json']
const BABELRC_JS = [
'.babelrc.js',
'.babelrc.cjs',
'.babelrc.mjs',
'babel.config.js',
'babel.config.cjs',
'babel.config.mjs',
]
const PKG = 'package.json'
const readConfigJs = fp => {
try {
// eslint-disable-next-line global-require,import/no-dynamic-require
const configModule = require(fp)
return configModule && configModule.__esModule
? configModule.default || undefined
: configModule
} catch (error) {
error.message = `${fp}: Error while loading config = ${error.message}`
throw error
}
}
const loadConfig = fp => {
const file = path.basename(fp)
const obj = fs.readFileSync(fp, 'utf-8')
const matchBabelRc = /^(?<babelrc>\.babelrc(?:.json|$)|babel\.config\.json)$/giu
const matchBabelRcJs = /^(?<babelrc>\.babelrc|babel\.config)[.](?:js|cjs|mjs)$/giu
switch (file) {
case matchBabelRcJs.test(file) ? file : null:
return readConfigJs(fp)
case matchBabelRc.test(file) ? file : null:
return json5.parse(obj)
case PKG:
return JSON.parse(obj).babel
default:
return {}
}
}
module.exports = opts => {
return findUp([...BABELRC, ...BABELRC_JS, PKG], opts).then(fp => {
if (!fp) {
return {}
}
const babel = loadConfig(fp)
return { babel, path: fp }
})
}
module.exports.sync = opts => {
const fp = findUp.sync([...BABELRC, ...BABELRC_JS, PKG], opts)
if (!fp) {
return {}
}
const babel = loadConfig(fp)
return { babel, path: fp }
}