-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
60 lines (50 loc) · 2.13 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
module.exports = function babelPluginModularGraphql({ types: t }, options = {}) {
let extension = (options.extension || '').trim();
if (extension && extension[0] !== '.') {
extension = '.' + extension;
}
const importMap = require('./import-map.json');
const indexRe = /[\\/]index$/;
const PKG_NAME = 'graphql';
return {
visitor: {
ImportDeclaration: {
exit(path) {
const { node } = path;
if (node.source.value !== PKG_NAME || !node.specifiers.length) return;
const imports = node.specifiers.reduce((acc, specifier) => {
if (t.isImportSpecifier(specifier)) {
const imported = specifier.imported.name;
let declaration = importMap[imported];
if (!declaration) {
console.warn(
`The export "${imported}" could not be found. It may not be known, or may not be available consistently between graphql@14|15|16.\n` +
'Try using an alternative method or check whether this method is present in the provided range of graphql major releases.'
);
}
let from = declaration ? declaration.from : PKG_NAME;
if (!acc[from]) {
if (from !== PKG_NAME && extension) {
from += extension;
} else if (from !== PKG_NAME && from.endsWith('')) {
from = from.replace(indexRe, '');
}
acc[from] = t.importDeclaration([], t.stringLiteral(from));
}
const localName = specifier.local.name;
const newImportedName = declaration ? declaration.local : imported;
acc[from].specifiers.push(
t.importSpecifier(t.identifier(localName), t.identifier(newImportedName))
);
}
return acc;
}, {});
const importFiles = Object.keys(imports);
if (importFiles.length && (importFiles.length !== 1 || importFiles[0] !== PKG_NAME)) {
path.replaceWithMultiple(importFiles.map((key) => imports[key]));
}
},
},
},
};
};