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.

Revisions

  1. silouanwright created this gist May 27, 2020.
    66 changes: 66 additions & 0 deletions classnames-to-classcat.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    // 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();
    };