Skip to content

Instantly share code, notes, and snippets.

@popomore
Created April 26, 2017 14:07
Show Gist options
  • Select an option

  • Save popomore/193d5c892bbf917a2882067aca8df745 to your computer and use it in GitHub Desktop.

Select an option

Save popomore/193d5c892bbf917a2882067aca8df745 to your computer and use it in GitHub Desktop.

Revisions

  1. popomore revised this gist Apr 26, 2017. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion jscodeshift-rename-property.js
    Original file line number Diff line number Diff line change
    @@ -34,7 +34,6 @@ function updateNode(node, name) {
    case 'Identifier':
    node.name = name;
    break;
    // exports['security-client']
    case 'Literal':
    node.value = name;
    break;
  2. popomore created this gist Apr 26, 2017.
    43 changes: 43 additions & 0 deletions jscodeshift-rename-property.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    'use strict';

    const jscodeshift = require('jscodeshift');
    const { MemberExpression, Property } = jscodeshift;

    jscodeshift.registerMethods({
    // exports.a => exports.b
    //
    // jscodeshift(source)
    // .find(jscodeshift.Identifier, { name: 'a' })
    // .renamePropertyTo('b');
    renamePropertyTo(name) {
    return this.replaceWith(nodePath => {
    const { node, parentPath } = nodePath;
    const parentNode = parentPath.value;

    // exports.a
    if (MemberExpression.check(parentPath.value) && parentNode.property.name === node.name) {
    updateNode(node, name);
    }

    // { a: 1 }
    if (Property.check(parentPath.value) && parentNode.key.value === node.value) {
    updateNode(node, name);
    }

    return node;
    });
    },
    });

    function updateNode(node, name) {
    switch (node.type) {
    case 'Identifier':
    node.name = name;
    break;
    // exports['security-client']
    case 'Literal':
    node.value = name;
    break;
    default:
    }
    }