Skip to content

Instantly share code, notes, and snippets.

@fersilva16
Last active November 19, 2021 00:33
Show Gist options
  • Save fersilva16/de64ca80d3e33efbd2ad3fe6ac8807e1 to your computer and use it in GitHub Desktop.
Save fersilva16/de64ca80d3e33efbd2ad3fe6ac8807e1 to your computer and use it in GitHub Desktop.
Transform `path.join` to string literal
import {
API,
ASTPath,
CallExpression,
FileInfo,
Literal,
MemberExpression,
StringLiteral,
VariableDeclaration
} from 'jscodeshift'
export default function transform(fileInfo: FileInfo, { jscodeshift }: API) {
const root = jscodeshift(fileInfo.source);
root.find(CallExpression, {
callee: {
type: 'MemberExpression',
object: {
type: 'Identifier',
name: 'path'
},
property: {
type: 'Identifier',
name: 'join'
},
}
})
.replaceWith<StringLiteral>((path: ASTPath<CallExpression>) => {
const literals = path.node.arguments.filter((argument) => argument.type === 'Literal') as Literal[];
return {
type: 'StringLiteral',
value: literals.map((literal) => literal.value).join('/'),
};
})
const pathExpressions = root.find(MemberExpression, {
object: {
type: 'Identifier',
name: 'path'
},
});
if (!pathExpressions.length) {
root.find(VariableDeclaration, {
kind: 'const',
declarations: [
{
type: 'VariableDeclarator',
id: {
type: 'Identifier',
name: 'path',
},
init: {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'require'
},
arguments: [
{
type: 'Literal',
value: 'path',
}
]
}
}
],
}).remove()
}
return root.toSource({ quote: 'single' });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment