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