-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
82 lines (68 loc) · 2.14 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
73
74
75
76
77
78
79
80
81
82
// @flow
'use strict';
const fs = require('fs');
const { loadFileSync, resolveImportFilePathSync } = require('babel-file-loader');
const { sync: resolveSync } = require('resolve');
const path = require('path');
/*::
import type { BabelParserOptions } from 'babel-flow-types';
export type ParserOptions = BabelParserOptions;
export type ResolveOptions = {
package?: Object,
extensions?: Array<string>,
readFile?: Function,
isFile?: Function,
packageFilter?: Function,
pathFilter?: Function,
paths?: Array<string>,
moduleDirectory?: string | Array<string>,
};
*/
function getImportSources(filePath, parserOpts, extensions) {
let importSources = [];
if (extensions.indexOf(path.extname(filePath).replace('.', ''))> -1 ) {
let file = loadFileSync(filePath, parserOpts);
for (let item of file.path.get('body')) {
if (item.isImportDeclaration() || (item.isExportDeclaration() && item.node.source)) {
importSources.push(item.node.source.value);
}
}
}
return importSources;
}
function resolveImportSourcePathSync(filePath, importSource, resolveOpts) {
return resolveSync(importSource, Object.assign({}, resolveOpts, {
basedir: path.dirname(filePath),
}));
}
const INTERNAL_MODULE_SOURCE = /^\./;
function collectImportsSync(
entry /*: string */,
options /*: { extensions: Array<string> } */ = { extensions: ['js', 'jsx', 'babel'] },
parserOpts /*:: ?: ParserOptions */,
resolveOpts /*:: ?: ResolveOptions */
) {
let visited = {};
let queue = [entry];
let internal = [];
let external = [];
while (queue.length) {
let filePath = queue.shift();
let importSources = getImportSources(filePath, parserOpts, options.extensions);
for (let importSource of importSources) {
if (INTERNAL_MODULE_SOURCE.test(importSource)) {
let resolved = resolveImportSourcePathSync(filePath, importSource, resolveOpts);
if (!visited[resolved]) queue.push(resolved);
} else {
external.push(importSource)
}
}
internal.push(filePath);
visited[filePath] = true;
}
return {
internal,
external,
};
}
exports.collectImportsSync = collectImportsSync;