Say I have the following code I want to transform:
export default () => {}; The following visitor code works:
export default function ({ types: t }) { return { visitor: { ArrowFunctionExpression(path) { if (!path.node.body.directives.some(d => d.value.value === 'inject')) return; path.node.body.directives = path.node.body.directives.filter(d => d.value.value !== 'inject'); path.replaceWith(t.arrayExpression([path.node])); } } }; } That results in the following output:
export default [() => {}]; Great! Now change the input:
export default function () { 'inject'; }; And the visitor:
export default function ({types: t}) { return { visitor: { FunctionDeclaration(path) { if (!path.node.body.directives.some(d => d.value.value === 'inject')) return; path.node.body.directives = path.node.body.directives.filter(d => d.value.value !== 'inject'); path.replaceWith(t.arrayExpression([path.node])); } } }; } That produces the following error:
TypeError: unknown: Property elements[0] of ArrayExpression expected node to be of a type ["null","Expression","SpreadElement"] but instead got "FunctionDeclaration"
Okay, so convert the FunctionDeclaration to a FunctionExpression:
export default function ({types: t}) { return { visitor: { FunctionDeclaration(path) { if (!path.node.body.directives.some(d => d.value.value === 'inject')) return; path.node.body.directives = path.node.body.directives.filter(d => d.value.value !== 'inject'); path.replaceWith( t.arrayExpression([ t.functionExpression(path.node.id, path.node.params, path.node.body, path.node.generator, path.node.async), ]) ); } } }; } And I get the following error:
TypeError: unknown: Property declaration of ExportDefaultDeclaration expected node to be of a type ["FunctionDeclaration","ClassDeclaration","Expression"] but instead got "ExpressionStatement"
And that is where I'm lost. I'm creating an ArrayExpression just as I was with the default-exported arrow function. Why is it complaining about receiving an ExpressionStatement?
Note, the desired output is as such:
export default [function () { }];