Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
// ast-pretty-print is really handy :)
const printAST = require('ast-pretty-print')
const {createMacro} = require('babel-macros')
module.exports = createMacro(greetingMacro)
function greetingMacro({references, babel}) {
const {default: hello = [], goodbye = []} = references
hello.forEach(reference => {
// console.log(printAST(reference))
reference.replaceWith(babel.types.stringLiteral('hi there'))
})
goodbye.forEach(reference => {
// console.log(printAST(reference))
reference.replaceWith(babel.types.stringLiteral('goodbye friend'))
})
}
(TEMP_VAR = NODE, UNWRAP)
`);
const createUnwrapExpression = (id) =>
buildUnwrapExpression({
WRAPPED: id
});
const createUnwrapSequence = (id, node) =>
buildUnwrapSequence({
TEMP_VAR: id,
NODE: node,
UNWRAP: createUnwrapExpression(id)
});
module.exports = createMacro(({ references }) => {
const refs = references.default.slice(0).reverse();
refs.forEach(path => {
const id = t.identifier('_wrappedValue');
const maybeValueNode = path.parentPath.node.arguments[0];
const valueNode = maybeValueNode !== undefined ?
maybeValueNode :
t.identifier('undefined');
if (valueNode.type === 'Identifier') {
path.parentPath.replaceWith(
createUnwrapExpression(valueNode)
);
} else {
path.parentPath.replaceWith(
createUnwrapSequence(id, valueNode)
);
ensureVar(id, path);
};
const macro = ({ references, state }) => {
const paths = getPaths(state.file.opts.filename);
Object.keys(paths).forEach(key => {
const value = (key === 'default' ? paths['base'] : paths[key]) || '';
const list = references[key] || [];
list.forEach(reference => {
reference.replaceWithSourceString(JSON.stringify(value));
});
})
};
module.exports = createMacro(macro);