Mirror: Modular GraphQL.js import paths without the hassle.
1export default function({ types: t }) {
2 const importMap = require('./import-map.json');
3 const PKG_NAME = 'graphql';
4
5 return {
6 visitor: {
7 ImportDeclaration: {
8 exit(path) {
9 const { node } = path;
10 if (node.source.value !== PKG_NAME || !node.specifiers.length) return;
11
12 const imports = node.specifiers.reduce((acc, specifier) => {
13 if (t.isImportSpecifier(specifier)) {
14 const imported = specifier.imported.name;
15 const declaration = importMap[imported];
16 const from = declaration ? declaration.from : PKG_NAME;
17 if (!acc[from]) {
18 acc[from] = t.importDeclaration([], t.stringLiteral(from));
19 }
20
21 const localName = specifier.local.name;
22 const newImportedName = declaration ? declaration.local : imported;
23
24 acc[from].specifiers.push(
25 t.importSpecifier(
26 t.identifier(localName),
27 t.identifier(newImportedName)
28 )
29 );
30 }
31
32 return acc;
33 }, {});
34
35 const importFiles = Object.keys(imports);
36 if (
37 importFiles.length &&
38 (importFiles.length !== 1 || importFiles[0] !== PKG_NAME)
39 ) {
40 path.replaceWithMultiple(importFiles.map(key => imports[key]));
41 }
42 },
43 },
44 },
45 };
46}