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 indexRe = /[\\/]index$/; 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 (!declaration) { 24 console.warn( 25 `The export "${imported}" could not be found. It may not be known, or may not be available consistently between graphql@14|15|16.\n` + 26 'Try using an alternative method or check whether this method is present in the provided range of graphql major releases.' 27 ); 28 } 29 30 let from = declaration ? declaration.from : PKG_NAME; 31 if (!acc[from]) { 32 if (from !== PKG_NAME && extension) { 33 from += extension; 34 } else if (from !== PKG_NAME && from.endsWith('')) { 35 from = from.replace(indexRe, ''); 36 } 37 38 acc[from] = t.importDeclaration([], t.stringLiteral(from)); 39 } 40 41 const localName = specifier.local.name; 42 const newImportedName = declaration ? declaration.local : imported; 43 44 acc[from].specifiers.push( 45 t.importSpecifier(t.identifier(localName), t.identifier(newImportedName)) 46 ); 47 } 48 49 return acc; 50 }, {}); 51 52 const importFiles = Object.keys(imports); 53 if (importFiles.length && (importFiles.length !== 1 || importFiles[0] !== PKG_NAME)) { 54 path.replaceWithMultiple(importFiles.map((key) => imports[key])); 55 } 56 }, 57 }, 58 }, 59 }; 60};