Skip to content

Instantly share code, notes, and snippets.

@euvs
Created February 19, 2021 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save euvs/a72552c6377ddc379dcde9e269eefb6a to your computer and use it in GitHub Desktop.
Save euvs/a72552c6377ddc379dcde9e269eefb6a to your computer and use it in GitHub Desktop.
Babel plugin that injects twin.macro
import template from '@babel/template';
// template
const buildImport = template(`
import 'twin.macro';
`);
// const debug = console.log;
const debug = (args: any) => {};
// const styledComponentsMacroImport = 'styled-components/macro';
// plugin
export default function importTwinMarcoPlugin(babel) {
const importDeclaration = buildImport();
return {
visitor: {
Program: (path, state, fileName) => {
let shouldAddImport = true;
state.file.path.traverse({
ImportDeclaration(path) {
// Find the twin import path
if (path.node.source.value === 'twin.macro') {
shouldAddImport = false;
}
},
});
if (shouldAddImport) {
debug(`Injected \'import "twin.macro"\' [${state.file.opts.sourceFileName}]`);
path.unshiftContainer('body', importDeclaration);
} else {
debug(`Skipped twin.macro injection [${state.file.opts.sourceFileName}]`);
}
},
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment