Skip to content

Instantly share code, notes, and snippets.

@silouanwright
Created May 27, 2020 21:04
Show Gist options
  • Save silouanwright/e17ada1c068c972d410774b957ada75c to your computer and use it in GitHub Desktop.
Save silouanwright/e17ada1c068c972d410774b957ada75c to your computer and use it in GitHub Desktop.
Codemod to convert from classnames to classcat
// v.0.1.0
// This is a somewhat of a naive mod and can be improved.
module.exports = (file, api) => {
const j = api.jscodeshift; // alias the jscodeshift API
let root = j(file.source); // parse JS code into an AST
// Can we find an import path
const findImport = root.find(j.ImportDeclaration, {
specifiers: [
{
local: {
name: "cx"
}
}
],
source: { value: "classnames" }
});
// If we can't find that import, we don't want to process anything further
if (!findImport.__paths.length) return root.toSource();
root = root
.find(j.ImportDeclaration, {
specifiers: [
{
local: {
name: "cx"
}
}
],
source: {
value: "classnames"
}
})
.forEach((statement) => {
j(statement).replaceWith(
j.importDeclaration(
[j.importDefaultSpecifier(j.identifier("cc"))],
j.literal("classcat")
)
);
}) .toSource({quote: 'single'})
const sortArguments = (args) => {
return args.sort((a, b) => {
if (a.type === "ObjectExpression") {
return -1;
}
return 0;
});
};
root = j(root).find(j.CallExpression).forEach((statement) => {
if (statement.value.callee.name === "cx") {
sortArguments(statement.value.arguments);
j(statement).replaceWith(
j.callExpression(j.identifier("cc"), [
j.arrayExpression(sortArguments(statement.value.arguments))
])
);
}
});
return root.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment