/
babel.js
executable file
·99 lines (77 loc) · 2.48 KB
/
babel.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import path from 'path';
import lodash from 'lodash';
import { loadConfig } from '../utils/linters';
function parse(content) {
try {
return JSON.parse(content);
} catch (error) {
return {}; // ignore parse error silently
}
}
function isPlugin(target, plugin) {
return lodash.isString(target)
? target === plugin || target === `babel-plugin-${plugin}`
: target[0] === plugin || target[0] === `babel-plugin-${plugin}`;
}
function contain(array, dep, prefix, scope) {
if (!array) {
return false;
}
// extract name if wrapping with options
const names = array.map((item) => (lodash.isString(item) ? item : item[0]));
if (names.indexOf(dep) !== -1) {
return true;
}
const fullPrefix = scope ? `${scope}/${prefix}` : prefix;
if (prefix && dep.indexOf(fullPrefix) === 0) {
const identifier = dep.substring(fullPrefix.length);
return contain(array, scope ? `${scope}/${identifier}` : identifier, false);
}
return false;
}
function getReactTransforms(deps, plugins) {
const transforms = lodash(plugins || [])
.filter((plugin) => isPlugin(plugin, 'react-transform'))
.map(([, plugin]) => plugin.transforms.map(({ transform }) => transform))
.first();
return lodash.intersection(transforms, deps);
}
function filter(deps, options) {
const presets = deps.filter((dep) =>
contain(options.presets, dep, 'babel-preset-'),
);
const presets7 = deps.filter((dep) =>
contain(options.presets, dep, 'preset-', '@babel'),
);
const plugins = deps.filter((dep) =>
contain(options.plugins, dep, 'babel-plugin-'),
);
const plugins7 = deps.filter((dep) =>
contain(options.plugins, dep, 'plugin-', '@babel'),
);
const reactTransforms = getReactTransforms(deps, options.plugins);
return lodash.uniq(
presets.concat(presets7, plugins, plugins7, reactTransforms),
);
}
function checkOptions(deps, options = {}) {
const optDeps = filter(deps, options);
const envDeps = lodash(options.env)
.values()
.map((env) => filter(deps, env))
.flatten()
.value();
return optDeps.concat(envDeps);
}
const regex = /^(\.babelrc|babelrc\.js|babel\.config\.js)?$/;
export default function parseBabel(content, filePath, deps, rootDir) {
const config = loadConfig('babel', regex, filePath, content, rootDir);
if (config) {
return checkOptions(deps, config);
}
if (path.basename(filePath) === 'package.json') {
const metadata = parse(content);
return checkOptions(deps, metadata.babel);
}
return [];
}