How to use jscodeshift - 10 common examples

To help you get started, we’ve selected a few jscodeshift examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sibelius / graphql2ts / test / testUtils.ts View on Github external
function runInlineTest(module, options, input, expectedOutput) {
  // Handle ES6 modules using default export for the transform
  const transform = module.default ? module.default : module;

  // Jest resets the module registry after each test, so we need to always get
  // a fresh copy of jscodeshift on every test run.
  let jscodeshift = require('jscodeshift');
  if (module.parser) {
    jscodeshift = jscodeshift.withParser(module.parser);
  }

  const output = transform(
    input,
    {
      jscodeshift,
      stats: () => {},
    },
    options || {},
  );
  expect((output || '').trim()).toEqual(expectedOutput.trim());
}
exports.runInlineTest = runInlineTest;
github Polymer / tools / src / document-processor.ts View on Github external
node.body.body.splice(
            0,
            0,
            jsc.methodDefinition(
                'get',
                jsc.identifier('template'),
                jsc.functionExpression(
                    null, [], jsc.blockStatement([jsc.returnStatement(
                                  templateLiteral)])),
                true));
      } else if (node.type === 'CallExpression') {
        // A Polymer hybrid/legacy factory function element
        const arg = node.arguments[0];
        if (arg && arg.type === 'ObjectExpression') {
          arg.properties.unshift(jsc.property(
              'init', jsc.identifier('_template'), templateLiteral));
        }
      } else {
        console.error(`Internal Error, Class or CallExpression expected, got ${
            node.type}`);
      }
    }
    return claimedDomModules;
  }
github Polymer / tools / src / document-processor.ts View on Github external
if (!canDomModuleBeInlined(domModule)) {
        continue;
      }
      claimedDomModules.add(domModule);
      const template = dom5.query(domModule, (e) => e.tagName === 'template');
      if (template === null) {
        continue;
      }

      // It's ok to tag templates with the expression `Polymer.html` without
      // adding an import because `Polymer.html` is re-exported by both
      // polymer.html and polymer-element.html and, crucially, template
      // inlining happens before rewriting references.
      const templateLiteral = jsc.taggedTemplateExpression(
          jsc.memberExpression(
              jsc.identifier('Polymer'), jsc.identifier('html')),
          serializeNodeToTemplateLiteral(
              parse5.treeAdapters.default.getTemplateContent(template)));
      const nodePath = getNodePathInProgram(program, element.astNode);

      if (nodePath === undefined) {
        console.warn(
            new Warning({
              code: 'not-found',
              message: `Can't find recast node for element ${element.tagName}`,
              parsedDocument: this.document.parsedDocument,
              severity: Severity.WARNING,
              sourceRange: element.sourceRange!
            }).toString());
        continue;
      }
github dvajs / dva-ast / src / collections / RouteComponent.js View on Github external
// TODO: Support dispatch(routerRedux.push({''}));
      if (j.CallExpression.check(obj)) {
        console.warn(`[WARN] getActionTypeFromCall: don't support dispatch with CallExpression yet`);
        return null;
      }

      assert(
        obj.type === 'ObjectExpression',
        `getActionType: dispatch should be called with Object, but got ${node.type}`
      );
      const value = utils.getObjectProperty(obj, 'type');
      if (value.type === 'Literal') {
        return value.value;
      } else if (value.type === 'Identifier') {
        const result = j(path).getVariableDeclarators(_ => value.name);
        if (result.size()) {
          return result.get().value.init.value;
        } else {
          return UNRESOLVED_IDENTIFIER;
        }
      } else if (value.type === 'TemplateLiteral') {
        console.warn(`[WARN] getActionTypeFromCall: unsupported action type ${value.type}`);
      } else {
        throw new Error(`getActionTypeFromCall: unsupported action type ${value.type}`);
      }
    });
    return ret.filter(item => !!item);
github Polymer / tools / src / passes / rewrite-namespace-exports.ts View on Github external
isMutable ? 'let' : 'const', [jsc.variableDeclarator(key, value)]));
      (node as NodeWithComments).comments = getCommentsFromNode(propNode);
      exportRecords.push({name, node});
    } else if (value.type === 'FunctionExpression') {
      const func = value;
      const node = jsc.exportNamedDeclaration(jsc.functionDeclaration(
          key,  // id
          func.params,
          func.body,
          func.generator));
      (node as NodeWithComments).comments = getCommentsFromNode(propNode);
      exportRecords.push({name, node});
    } else if (value.type === 'ArrowFunctionExpression') {
      const isMutable =
          mutableNames.has(fullName) || mutableNames.has(thisName);
      const node = jsc.exportNamedDeclaration(jsc.variableDeclaration(
          isMutable ? 'let' : 'const', [jsc.variableDeclarator(key, value)]));
      (node as NodeWithComments).comments = getCommentsFromNode(propNode);
      exportRecords.push({name, node});
    } else if (value.type === 'Identifier') {
      const node = jsc.exportNamedDeclaration(
          null,
          [jsc.exportSpecifier(jsc.identifier(name), jsc.identifier(name))]);
      (node as NodeWithComments).comments = getCommentsFromNode(propNode);
      exportRecords.push({name, node});
    } else {
      console.warn('Namespace property not handled:', name, value);
    }
  }

  return exportRecords;
}
github Polymer / tools / packages / modulizer / src / passes / rewrite-namespace-exports.ts View on Github external
const exportRecords: {name: string, node: estree.Node}[] = [];

  for (const propNode of namespace.properties) {
    const {key, value} = propNode;
    if (key.type !== 'Identifier') {
      console.warn(`unsupported namespace property type ${key.type}`);
      continue;
    }
    const name = key.name;
    const fullName = `${namespaceName}.${name}`;
    // The expression for an internal `this.` reference to a namespace member
    const thisName = `this.${name}`;
    const isMutable = mutableNames.has(fullName) || mutableNames.has(thisName);
    if (value.type === 'ObjectExpression' || value.type === 'ArrayExpression' ||
        value.type === 'Literal') {
      const node = jsc.exportNamedDeclaration(jsc.variableDeclaration(
          isMutable ? 'let' : 'const', [jsc.variableDeclarator(key, value)]));
      (node as NodeWithComments).comments = getCommentsFromNode(propNode);
      exportRecords.push({name, node});
    } else if (value.type === 'FunctionExpression') {
      const func = value;
      const node = jsc.exportNamedDeclaration(jsc.functionDeclaration(
          key,  // id
          func.params,
          func.body,
          func.generator));
      (node as NodeWithComments).comments = getCommentsFromNode(propNode);
      exportRecords.push({name, node});
    } else if (value.type === 'ArrowFunctionExpression') {
      const isMutable =
          mutableNames.has(fullName) || mutableNames.has(thisName);
      const node = jsc.exportNamedDeclaration(jsc.variableDeclaration(
github Polymer / tools / src / passes / rewrite-namespace-exports.ts View on Github external
const node = jsc.exportNamedDeclaration(jsc.functionDeclaration(
          key,  // id
          func.params,
          func.body,
          func.generator));
      (node as NodeWithComments).comments = getCommentsFromNode(propNode);
      exportRecords.push({name, node});
    } else if (value.type === 'ArrowFunctionExpression') {
      const isMutable =
          mutableNames.has(fullName) || mutableNames.has(thisName);
      const node = jsc.exportNamedDeclaration(jsc.variableDeclaration(
          isMutable ? 'let' : 'const', [jsc.variableDeclarator(key, value)]));
      (node as NodeWithComments).comments = getCommentsFromNode(propNode);
      exportRecords.push({name, node});
    } else if (value.type === 'Identifier') {
      const node = jsc.exportNamedDeclaration(
          null,
          [jsc.exportSpecifier(jsc.identifier(name), jsc.identifier(name))]);
      (node as NodeWithComments).comments = getCommentsFromNode(propNode);
      exportRecords.push({name, node});
    } else {
      console.warn('Namespace property not handled:', name, value);
    }
  }

  return exportRecords;
}
github dvajs / dva-ast / src / api / router.js View on Github external
if (existsSync(componentFilePath)) {
    relativePath = relative(filePath, componentFilePath);
    if (relativePath.charAt(0) !== '.') {
      relativePath = './' + relativePath;
    }
    relativePath = relativePath.split(sep).join('/');  // workaround for windows
  }

  const imports = root.find(j.ImportDeclaration);
  const lastImport = imports.at(imports.size() - 1);
  lastImport.insertAfter(
    j.importDeclaration(
      [j.importDefaultSpecifier(
        j.identifier(component.componentName)
      )],
      j.literal(relativePath)
    )
  );
  writeFile(filePath, root.toSource());
}
github Polymer / tools / src / passes / rewrite-namespace-exports.ts View on Github external
const exportRecords: {name: string, node: estree.Node}[] = [];

  for (const propNode of namespace.properties) {
    const {key, value} = propNode;
    if (key.type !== 'Identifier') {
      console.warn(`unsupported namespace property type ${key.type}`);
      continue;
    }
    const name = key.name;
    const fullName = `${namespaceName}.${name}`;
    // The expression for an internal `this.` reference to a namespace member
    const thisName = `this.${name}`;
    const isMutable = mutableNames.has(fullName) || mutableNames.has(thisName);
    if (value.type === 'ObjectExpression' || value.type === 'ArrayExpression' ||
        value.type === 'Literal') {
      const node = jsc.exportNamedDeclaration(jsc.variableDeclaration(
          isMutable ? 'let' : 'const', [jsc.variableDeclarator(key, value)]));
      (node as NodeWithComments).comments = getCommentsFromNode(propNode);
      exportRecords.push({name, node});
    } else if (value.type === 'FunctionExpression') {
      const func = value;
      const node = jsc.exportNamedDeclaration(jsc.functionDeclaration(
          key,  // id
          func.params,
          func.body,
          func.generator));
      (node as NodeWithComments).comments = getCommentsFromNode(propNode);
      exportRecords.push({name, node});
    } else if (value.type === 'ArrowFunctionExpression') {
      const isMutable =
          mutableNames.has(fullName) || mutableNames.has(thisName);
      const node = jsc.exportNamedDeclaration(jsc.variableDeclaration(
github 5to6 / 5to6-codemod / utils / main.js View on Github external
singleVarToExpressions: function(ast) {
    // if ast.value, use that... Sometimes you need that to access the node that we care about directly.
    ast = ast.value || ast;

    var expressions = [];
    var declarations = ast.declarations;
    // safety checks
    // am I a single var statement?
    if (ast.type === 'VariableDeclaration' && ast.declarations.length > 1) {
      for (var i = 0; i < declarations.length; i++) {
        var varStatement = j.variableDeclaration('var', [ast.declarations[i]]);
        expressions.push(varStatement);
      }

      // console.log('expressions', expressions);
      return expressions;
      // console.log('inside');
      // console.log('varStatement', varStatement);
    } else {
      console.warn('ERROR: Expected a single var statement. THat\'s NOT what I got:');
      console.log('ast', ast);
    }
  },