forked from webpro-nl/knip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
44 lines (35 loc) · 1.7 KB
/
index.ts
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
import { compact } from '../../util/array.js';
import { timerify } from '../../util/Performance.js';
import { hasDependency, load } from '../../util/plugin.js';
import { resolvePresetName, resolvePluginName, api } from './helpers.js';
import type { BabelConfig, BabelConfigObj } from './types.js';
import type { IsPluginEnabledCallback, GenericPluginCallback } from '../../types/plugins.js';
// https://babeljs.io/docs/en/configuration
export const NAME = 'Babel';
/** @public */
export const ENABLERS = [/^@babel\//];
export const isEnabled: IsPluginEnabledCallback = ({ dependencies }) => hasDependency(dependencies, ENABLERS);
export const CONFIG_FILE_PATTERNS = [
'babel.config.json',
'babel.config.js',
'.babelrc.json',
'.babelrc.js',
'.babelrc',
'package.json',
];
const getItemName = (value: string | [string, unknown]) =>
typeof value === 'string' ? [value] : Array.isArray(value) ? [value[0]] : [];
export const getDependenciesFromConfig = (config: BabelConfigObj): string[] => {
const presets = config.presets?.flatMap(getItemName).map(resolvePresetName) ?? [];
const plugins = config.plugins?.flatMap(getItemName).map(resolvePluginName) ?? [];
const nested = config.env ? Object.values(config.env).flatMap(getDependenciesFromConfig) : [];
return compact([...presets, ...plugins, ...nested]);
};
const findBabelDependencies: GenericPluginCallback = async (configFilePath, { manifest }) => {
let config: BabelConfig = configFilePath.endsWith('package.json') ? manifest.babel : await load(configFilePath);
if (typeof config === 'function') {
config = config(api);
}
return config ? getDependenciesFromConfig(config) : [];
};
export const findDependencies = timerify(findBabelDependencies);