Last active
March 1, 2022 10:41
-
-
Save hanford/10401629eb7d82d47b275f59356d86f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-enable no-param-reassign */ | |
function genId() { | |
const num = uuid(); | |
return `graphql__${num}`; | |
} | |
function uuid() { | |
return 'xxxxxxxx'.replace(/[xy]/g, function (c) { | |
var r = (Math.random() * 16) | 0, | |
v = c == 'x' ? r : (r & 0x3) | 0x8; | |
return v.toString(16); | |
}); | |
} | |
module.exports = function (babel) { | |
const { types: t } = babel; | |
let gqlTags = []; | |
function TaggedTemplateExpression({ node, parent }) { | |
const isGraphql = node.tag.name === 'graphql'; | |
if (isGraphql) { | |
const moduleId = genId(); | |
const contents = node.quasi.quasis[0].value.raw.trim(); | |
const name = /(fragment|mutation|query) (\w+)/.exec(contents)[2]; | |
const nextValue = t.identifier(moduleId); | |
gqlTags.push({ name, id: moduleId }); | |
switch (parent.type) { | |
case 'ObjectProperty': | |
parent.value = nextValue; | |
return; | |
case 'VariableDeclarator': | |
parent.init = nextValue; | |
return; | |
case 'CallExpression': | |
parent.arguments[0] = nextValue; | |
return; | |
case 'JSXExpressionContainer': | |
parent.expression = nextValue; | |
return; | |
default: | |
} | |
} | |
} | |
return { | |
name: 'FF', // not required | |
visitor: { | |
Program: { | |
enter() { | |
// Reset variables when we enter a new file | |
gqlTags = []; | |
}, | |
exit(path) { | |
gqlTags.forEach(({ name, id }) => { | |
const identifier = t.identifier(id); | |
const importDefaultSpecifier = t.importDefaultSpecifier(identifier); | |
const importDeclaration = t.importDeclaration( | |
[importDefaultSpecifier], | |
t.stringLiteral(`dazzle-types/${name}.graphql`), | |
); | |
path.unshiftContainer('body', importDeclaration); | |
}); | |
}, | |
}, | |
TaggedTemplateExpression, | |
}, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/hanford/10401629eb7d82d47b275f59356d86f5#file-babel-plugin-relay-jack-js-L65 will probably need to be something else