當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript jscodeshift.identifier函數代碼示例

本文整理匯總了TypeScript中jscodeshift.identifier函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript identifier函數的具體用法?TypeScript identifier怎麽用?TypeScript identifier使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了identifier函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: rewriteSingleScopeThisReferences

/**
 * Rewrite `this` references to the explicit namespaceReference identifier
 * within a single BlockStatement if they are the start of a member expression,
 * otherwise they are rewritten to `undefined`. Don't traverse deeper into new
 * scopes.
 */
function rewriteSingleScopeThisReferences(
    blockStatement: estree.BlockStatement, namespaceReference: string) {
  astTypes.visit(blockStatement, {
    visitThisExpression(path: NodePath<estree.ThisExpression>) {
      const parent = path.parent;
      if (parent && parent.node.type !== 'MemberExpression') {
        // When a namespace object is itself referenced with `this` but isn't
        // used to reference a member of the namespace, rewrite the `this` to
        // `undefined`:
        path.replace(jsc.identifier('undefined'));
      } else {
        path.replace(jsc.identifier(namespaceReference));
      }
      return false;
    },

    visitFunctionExpression(_path: NodePath<estree.FunctionExpression>) {
      // Don't visit into new scopes
      return false;
    },
    visitFunctionDeclaration(_path: NodePath<estree.FunctionDeclaration>) {
      // Don't visit into new scopes
      return false;
    },
    visitMethodDefinition(_path: NodePath) {
      // Don't visit into new scopes
      return false;
    },
    // Note: we do visit into ArrowFunctionExpressions because they
    //     inherit the containing `this` context.
  });
}
開發者ID:,項目名稱:,代碼行數:38,代碼來源:

示例2: addImportMetaToElements

  /**
   * Adds a static importMeta property to Polymer elements.
   */
  private addImportMetaToElements(program: Program, scriptDocument: Document) {
    const elements = scriptDocument.getFeatures({'kind': 'polymer-element'});

    for (const element of elements) {
      // This is an analyzer wart. There's no way to avoid getting features
      // from the containing document when querying an inline document. Filed
      // as https://github.com/Polymer/polymer-analyzer/issues/712
      if (element.sourceRange === undefined ||
          !isPositionInsideRange(
              element.sourceRange.start, scriptDocument.sourceRange)) {
        continue;
      }

      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;
      }

      const importMeta = jsc.memberExpression(
          jsc.identifier('import'), jsc.identifier('meta'));

      const node = nodePath.node;
      if (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') {
        // A Polymer 2.0 class-based element
        const getter = jsc.methodDefinition(
            'get',
            jsc.identifier('importMeta'),
            jsc.functionExpression(
                null,
                [],
                jsc.blockStatement([jsc.returnStatement(importMeta)])),
            true);
        node.body.body.splice(0, 0, getter);
      } 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('importMeta'), importMeta));
        }
      } else {
        console.error(`Internal Error, Class or CallExpression expected, got ${
            node.type}`);
      }
    }
  }
開發者ID:,項目名稱:,代碼行數:58,代碼來源:

示例3: assignAlias

          .map((import_) => {
            const name = import_.name;
            const alias = assignAlias(import_, import_.name);

            if (alias === name) {
              return jsc.importSpecifier(jsc.identifier(name));
            } else {
              return jsc.importSpecifier(
                  jsc.identifier(name), jsc.identifier(alias));
            }
          });
開發者ID:,項目名稱:,代碼行數:11,代碼來源:

示例4: createDefaultConversionSettings

export function createDefaultConversionSettings(
    analysis: Analysis,
    options: PartialConversionSettings): ConversionSettings {
  // Configure "namespaces":
  const namespaces =
      new Set(getNamespaceNames(analysis).concat(options.namespaces || []));

  // Configure "packageEntrypoints":
  const packageEntrypoints = options.packageEntrypoints || new Map();

  // Configure "excludes":
  const excludes = new Set(
      [...(options.excludes || []), 'neon-animation/web-animations.html']);

  // Configure "referenceExcludes":
  const referenceExcludes = new Set(options.referenceExcludes || [
    'Polymer.DomModule',
    'Polymer.Settings',
    'Polymer.log',
    'Polymer.rootPath',
    'Polymer.sanitizeDOMValue',
    'Polymer.Collection',
  ]);

  // Configure "referenceRewrites":
  const referenceRewrites = new Map<string, estree.Node>([
    [
      'document.currentScript.ownerDocument',
      jsc.memberExpression(jsc.identifier('window'), jsc.identifier('document'))
    ],
  ]);

  // Configure "npmImportStyle":
  const npmImportStyle = options.npmImportStyle || 'path';

  // Configure "npmImportStyle", defaults to false
  const addImportMeta = options.addImportMeta === true;

  // Return configured settings.
  return {
    namespaces,
    packageEntrypoints,
    excludes,
    referenceExcludes,
    referenceRewrites,
    npmImportStyle,
    addImportMeta,
  };
}
開發者ID:,項目名稱:,代碼行數:49,代碼來源:

示例5: attachCommentsToFirstStatement

export function attachCommentsToFirstStatement(
    comments: string[],
    statements: Array<estree.Statement|estree.ModuleDeclaration>) {
  if (comments.length === 0) {
    return;
  }
  // A license comment is appropriate at the top of a file. Anything else
  //   should be checked.
  if (comments.filter((c) => !/@license/.test(c)).length > 0) {
    const message =
        `\n  FIXME(polymer-modulizer): the above comments were extracted\n` +
        `  from HTML and may be out of place here. Review them and\n` +
        `  then delete this comment!\n`;
    comments.push(message);
  }

  const recastComments = getCommentsFromTexts(comments);
  let firstStatement: RecastNode&(estree.Statement | estree.ModuleDeclaration) =
      statements[0];
  if (firstStatement === undefined) {
    firstStatement = jsc.expressionStatement(jsc.identifier(''));
    statements.unshift(firstStatement);
  }

  firstStatement.comments =
      recastComments.concat(firstStatement.comments || []);
}
開發者ID:,項目名稱:,代碼行數:27,代碼來源:

示例6: createDomNodeInsertStatements

export function createDomNodeInsertStatements(
    nodes: parse5.ASTNode[], activeInBody = false): estree.Statement[] {
  const varName = `$_documentContainer`;
  const fragment = {
    nodeName: '#document-fragment',
    attrs: [],
    childNodes: nodes,
    __location: {} as parse5.ElementLocationInfo,
  };
  const templateValue = serializeNodeToTemplateLiteral(fragment, false);

  const createElementTemplate = jsc.variableDeclaration(
      'const',
      [jsc.variableDeclarator(
          jsc.identifier(varName),
          jsc.callExpression(
              jsc.memberExpression(
                  jsc.identifier('document'), jsc.identifier('createElement')),
              [jsc.literal('template')]))]);
  const setDocumentContainerStatement =
      jsc.expressionStatement(jsc.assignmentExpression(
          '=',
          jsc.memberExpression(
              jsc.identifier(varName), jsc.identifier('innerHTML')),
          templateValue));
  const targetNode = activeInBody ? 'body' : 'head';
  return [
    createElementTemplate,
    setDocumentContainerStatement,
    jsc.expressionStatement(jsc.callExpression(
        jsc.memberExpression(
            jsc.memberExpression(
                jsc.identifier('document'), jsc.identifier(targetNode)),
            jsc.identifier('appendChild')),
        [jsc.memberExpression(
            jsc.identifier(varName), jsc.identifier('content'))]))
  ];
}
開發者ID:,項目名稱:,代碼行數:38,代碼來源:

示例7: attachCommentsToEndOfProgram

export function attachCommentsToEndOfProgram(
    comments: string[],
    statements: Array<estree.Statement|estree.ModuleDeclaration>) {
  if (comments.length === 0) {
    return;
  }
  const message =
      `\n  FIXME(polymer-modulizer): the above comments were extracted\n` +
      `  from HTML and may be out of place here. Review them and\n` +
      `  then delete this comment!\n`;
  comments.push(message);

  const recastComments = getCommentsFromTexts(comments);
  const lastStatement =
      jsc.expressionStatement(jsc.identifier('')) as RecastNode &
      estree.Statement;
  lastStatement.comments =
      (lastStatement.comments || []).concat(recastComments);
  statements.push(lastStatement);
}
開發者ID:,項目名稱:,代碼行數:20,代碼來源:

示例8: rewriteReferencesToLocalExports

export function rewriteReferencesToLocalExports(
    program: estree.Program,
    exportMigrationRecords: Iterable<NamespaceMemberToExport>) {
  const rewriteMap = new Map<string|undefined, string>(
      IterableX.from(exportMigrationRecords)
          .filter((m) => m.es6ExportName !== '*')
          .map(
              (m) => [m.oldNamespacedName,
                      m.es6ExportName] as [string, string]));
  astTypes.visit(program, {
    visitMemberExpression(path: NodePath<estree.MemberExpression>) {
      const memberName = getMemberName(path.node);
      const newLocalName = rewriteMap.get(memberName);
      if (newLocalName) {
        path.replace(jsc.identifier(newLocalName));
        return false;
      }
      this.traverse(path);
      return;
    }
  });
}
開發者ID:,項目名稱:,代碼行數:22,代碼來源:

示例9: rewriteExcludedReferences

export function rewriteExcludedReferences(
    program: estree.Program, settings: ConversionSettings) {
  const mapOfRewrites = new Map(settings.referenceRewrites);
  for (const reference of settings.referenceExcludes) {
    mapOfRewrites.set(reference, jsc.identifier('undefined'));
  }

  /**
   * Rewrite the given path of the given member by `mapOfRewrites`.
   *
   * Never rewrite an assignment to assign to `undefined`.
   */
  const rewrite = (path: NodePath, memberName: string) => {
    const replacement = mapOfRewrites.get(memberName);
    if (replacement) {
      if (replacement.type === 'Identifier' &&
          replacement.name === 'undefined' && isAssigningTo(path)) {
        /**
         * If `path` is a name / pattern that's being written to, we don't
         * want to rewrite it to `undefined`.
         */
        return;
      }
      path.replace(replacement);
    }
  };

  astTypes.visit(program, {
    visitMemberExpression(path: NodePath<estree.MemberExpression>) {
      const memberPath = getMemberPath(path.node);
      if (memberPath !== undefined) {
        rewrite(path, memberPath.join('.'));
      }
      this.traverse(path);
    },
  });
}
開發者ID:,項目名稱:,代碼行數:37,代碼來源:

示例10: addA11ySuiteIfUsed

export function addA11ySuiteIfUsed(
    program: estree.Program, a11ySuiteUrl: string): boolean {
  let isFound = false;
  astTypes.visit(program, {
    visitCallExpression(path: NodePath<estree.CallExpression>) {
      const callee = path.node.callee as estree.Identifier;
      const name = callee.name;
      if (name === 'a11ySuite') {
        isFound = true;
        this.abort();
      }
      this.traverse(path);
    }
  });

  if (!isFound) {
    return false;
  }

  program.body.unshift(jsc.importDeclaration(
      [jsc.importSpecifier(jsc.identifier('a11ySuite'))],
      jsc.literal(a11ySuiteUrl)));
  return true;
}
開發者ID:,項目名稱:,代碼行數:24,代碼來源:


注:本文中的jscodeshift.identifier函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。