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