Created
February 19, 2021 10:12
-
-
Save euvs/a72552c6377ddc379dcde9e269eefb6a to your computer and use it in GitHub Desktop.
Babel plugin that injects twin.macro
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
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