Mirror: Modular GraphQL.js import paths without the hassle.
1module.exports = function babelPluginModularGraphql({ 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(t.identifier(localName), t.identifier(newImportedName))
26 );
27 }
28
29 return acc;
30 }, {});
31
32 const importFiles = Object.keys(imports);
33 if (importFiles.length && (importFiles.length !== 1 || importFiles[0] !== PKG_NAME)) {
34 path.replaceWithMultiple(importFiles.map((key) => imports[key]));
35 }
36 },
37 },
38 },
39 };
40};