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


TypeScript traverse.default函數代碼示例

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


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

示例1: extractStyles


//.........這裏部分代碼省略.........

  // Generate a UID that's unique in the program scope
  let boxComponentName: string | undefined;
  traverse(ast, {
    Program(traversePath: TraversePath) {
      boxComponentName = generateUid(traversePath.scope, 'Box');
    },
  });

  // per-file cache of evaluated bindings
  const bindingCache = {};

  const traverseOptions: { JSXElement: VisitNodeObject<t.JSXElement> } = {
    JSXElement: {
      enter(traversePath: TraversePath<t.JSXElement>) {
        const node = traversePath.node.openingElement;

        if (
          // skip non-identifier opening elements (member expressions, etc.)
          !t.isJSXIdentifier(node.name) ||
          // skip non-jsxstyle components
          !validComponents.hasOwnProperty(node.name.name)
        ) {
          return;
        }

        // Remember the source component
        const originalNodeName = node.name.name;
        const srcKey = validComponents[originalNodeName];

        node.name.name = boxComponentName!;

        // prepend initial styles
        const initialStyles = defaultStyleAttributes[srcKey];
        if (initialStyles) {
          node.attributes = [...initialStyles, ...node.attributes];
        }

        const attemptEval = !evaluateVars
          ? evaluateAstNode
          : (() => {
              // Generate scope object at this level
              const staticNamespace = getStaticBindingsForScope(
                traversePath.scope,
                whitelistedModules,
                sourceFileName,
                bindingCache
              );

              const evalContext = vm.createContext(staticNamespace);

              // called when evaluateAstNode encounters a dynamic-looking prop
              const evalFn = (n: t.Node) => {
                // variable
                if (t.isIdentifier(n)) {
                  invariant(
                    staticNamespace.hasOwnProperty(n.name),
                    'identifier not in staticNamespace'
                  );
                  return staticNamespace[n.name];
                }
                return vm.runInContext(`(${generate(n).code})`, evalContext);
              };

              return (n: t.Node) => evaluateAstNode(n, evalFn);
            })();
開發者ID:petehunt,項目名稱:jsxstyle,代碼行數:67,代碼來源:extractStyles.ts

示例2: process

export default function process(source: string, ast: t.File): Changes {
  const tokens: Array<Token> = ast.tokens;
  const insertions: Array<Insertion> = [];
  const removals: Array<Removal> = [];

  traverse(ast, {
    VariableDeclaration(path: NodePath<t.VariableDeclaration>): void {
      const { node, parent } = path;
      const isForInit = (
        (t.isForStatement(parent)  && parent.init === node) ||
        ((t.isForInStatement(parent) || t.isForOfStatement(parent)) && parent.left === node)
      );

      if (!isForInit) {
        checkForSemicolon(node);
      }
    },

    ExpressionStatement(path: NodePath<t.ExpressionStatement>): void {
      checkForSemicolon(path.node);
    },

    ReturnStatement(path: NodePath<t.ReturnStatement>): void {
      checkForSemicolon(path.node);
    },

    ThrowStatement(path: NodePath<t.ThrowStatement>): void {
      checkForSemicolon(path.node);
    },

    DoWhileStatement(path: NodePath<t.DoWhileStatement>): void {
      checkForSemicolon(path.node);
    },

    DebuggerStatement(path: NodePath<t.DebuggerStatement>): void {
      checkForSemicolon(path.node);
    },

    BreakStatement(path: NodePath<t.BreakStatement>): void {
      checkForSemicolon(path.node);
    },

    ContinueStatement(path: NodePath<t.ContinueStatement>): void {
      checkForSemicolon(path.node);
    },

    ImportDeclaration(path: NodePath<t.ImportDeclaration>): void {
      checkForSemicolon(path.node);
    },

    ExportAllDeclaration(path: NodePath<t.ExportAllDeclaration>): void {
      checkForSemicolon(path.node);
    },

    ExportNamedDeclaration(path: NodePath<t.ExportNamedDeclaration>): void {
      if (!path.node.declaration) {
        checkForSemicolon(path.node);
      }
    },

    ExportDefaultDeclaration(path: NodePath<t.ExportDefaultDeclaration>): void {
      const { node } = path;
      const { declaration } = node;

      if (t.isClassDeclaration(declaration) || t.isFunctionDeclaration(declaration)) {
        if (!declaration.id) {
          checkForSemicolon(node);
        }
      } else {
        checkForSemicolon(node);
      }
    },

    EmptyStatement(path: NodePath<t.EmptyStatement>): void {
      const { node, parent } = path;

      if (
        !t.isForStatement(parent) &&
        !t.isForOfStatement(parent) &&
        !t.isForInStatement(parent) &&
        !t.isWhileStatement(parent) &&
        !t.isDoWhileStatement(parent)
      ) {
        remove(startOfNode(node), endOfNode(node));
      }
    },

    ClassBody(path: NodePath<t.ClassBody>): void {
      checkClassBodyForSemicolon(tokenAfterToken(firstTokenOfNode(path.node)));
    },

    ClassMethod(path: NodePath<t.ClassMethod>): void {
      checkClassBodyForSemicolon(tokenAfterToken(lastTokenOfNode(path.node)));
    }
  });

  return { insertions, removals };

  /**
   * Checks a node to see if it's followed by a semicolon.
//.........這裏部分代碼省略.........
開發者ID:eventualbuddha,項目名稱:automatic-semicolon-insertion,代碼行數:101,代碼來源:index.ts

示例3: traverse

export function traverse(ast: babel.Node, visitor: Visitor): void {
  babelTraverse(ast, {
    enter(path) {
      dispatchVisitMethods(
          ['enter', `enter${path.type}` as keyof Visitor], path, visitor);
    },

    exit(path) {
      dispatchVisitMethods(
          ['leave', `leave${path.type}` as keyof Visitor], path, visitor);
    },
    noScope: !babel.isFile(ast),
  });
}
開發者ID:MehdiRaash,項目名稱:tools,代碼行數:14,代碼來源:estraverse-shim.ts

示例4: inferReturnFromBody

export function inferReturnFromBody(node: babel.Function): {type: string}|
    undefined {
  if (node.async === true || node.generator === true) {
    // Async functions always return promises, and generators always return
    // iterators, so they are never void.
    return undefined;
  }
  if (babel.isArrowFunctionExpression(node) &&
      !babel.isBlockStatement(node.body)) {
    // An arrow function that immediately returns a value (e.g. () => 'foo').
    return undefined;
  }
  let returnsVoid = true;
  babelTraverse(node, {
    ReturnStatement(path) {
      const statement = path.node;
      // The typings claim that statement.argument is always an Expression, but
      // actually when there is no argument it is null.
      if (statement.argument !== null) {
        returnsVoid = false;
        path.stop();
      }
    },
    // If this function contains another function, don't traverse into it. Only
    // return statements in the immediate function scope matter.
    FunctionDeclaration(path) {
      path.skip();
    },
    FunctionExpression(path) {
      path.skip();
    },
    ClassMethod(path) {
      path.skip();
    },
    ArrowFunctionExpression(path) {
      path.skip();
    },
    ObjectMethod(path) {
      path.skip();
    },

    noScope: true
  });
  if (returnsVoid) {
    return {type: 'void'};
  }
  return undefined;
}
開發者ID:Polymer,項目名稱:tools,代碼行數:48,代碼來源:esutil.ts

示例5: getEventComments

export function getEventComments(node: babel.Node): Map<string, ScannedEvent> {
  const eventComments = new Set<string>();

  babelTraverse(node, {
    enter(path: NodePath) {
      const node = path.node;
      [...(node.leadingComments || []), ...(node.trailingComments || [])]
          .map((commentAST) => commentAST.value)
          .filter((comment) => comment.indexOf('@event') !== -1)
          .forEach((comment) => eventComments.add(comment));
    },
    noScope: true,
  });
  const events = [...eventComments]
                     .map(
                         (comment) => annotateEvent(jsdoc.parseJsdoc(
                             jsdoc.removeLeadingAsterisks(comment).trim())))
                     .filter((ev) => !!ev)
                     .sort((ev1, ev2) => ev1.name.localeCompare(ev2.name));
  return new Map(events.map((e) => [e.name, e] as [string, ScannedEvent]));
}
開發者ID:Polymer,項目名稱:tools,代碼行數:21,代碼來源:esutil.ts

示例6: Error

describe('getSourceModule', () => {
  const ast = parse(`
const Thing1 = require('thing');
const {Destructured1} = require('destructured');
const {Original: Reassigned1} = require('reassigned');

import Thing2 from 'thing';
import {Destructured2} from 'destructured';
import {Original as Reassigned2} from 'reassigned';

<Thing1 />;
<Thing2 />;
<Destructured1 />;
<Destructured2 />;
<Reassigned1 />;
<Reassigned2 />;
`);

  const testItems: Record<string, any> = {};
  traverse(ast, {
    JSXElement(path) {
      const node = path.node.openingElement;
      const nodeName = node.name;
      if (!t.isJSXIdentifier(nodeName)) {
        throw new Error(
          'Received invalid node name: ' + generate(node.name).code
        );
      }
      testItems[nodeName.name] = {
        node,
        scope: path.scope,
      };
    },
  });

  it('traverses the source correctly', () => {
    expect(Object.keys(testItems)).toEqual([
      'Thing1',
      'Thing2',
      'Destructured1',
      'Destructured2',
      'Reassigned1',
      'Reassigned2',
    ]);
  });

  it('handles regular requires', () => {
    const { node, scope } = testItems.Thing1;
    const itemName = node.name.name;
    const sourceModule = getSourceModuleForItem(itemName, scope);

    expect(sourceModule).not.toBeNull();
    expect(sourceModule.destructured).toEqual(false);
    expect(sourceModule.imported).toEqual('Thing1');
    expect(sourceModule.local).toEqual('Thing1');
    expect(sourceModule.sourceModule).toEqual('thing');
  });

  it('handles destructured requires', () => {
    const { node, scope } = testItems.Destructured1;
    const itemName = node.name.name;
    const sourceModule = getSourceModuleForItem(itemName, scope);

    expect(sourceModule).not.toBeNull();
    expect(sourceModule.destructured).toEqual(true);
    expect(sourceModule.imported).toEqual('Destructured1');
    expect(sourceModule.local).toEqual('Destructured1');
    expect(sourceModule.sourceModule).toEqual('destructured');
  });

  it('handles reassigned requires', () => {
    const { node, scope } = testItems.Reassigned1;
    const itemName = node.name.name;
    const sourceModule = getSourceModuleForItem(itemName, scope);

    expect(sourceModule).not.toBeNull();
    expect(sourceModule.destructured).toEqual(true);
    expect(sourceModule.imported).toEqual('Original');
    expect(sourceModule.local).toEqual('Reassigned1');
    expect(sourceModule.sourceModule).toEqual('reassigned');
  });

  it('handles regular imports', () => {
    const { node, scope } = testItems.Thing2;
    const itemName = node.name.name;
    const sourceModule = getSourceModuleForItem(itemName, scope);

    expect(sourceModule).not.toBeNull();
    expect(sourceModule.destructured).toEqual(false);
    expect(sourceModule.imported).toEqual('Thing2');
    expect(sourceModule.local).toEqual('Thing2');
    expect(sourceModule.sourceModule).toEqual('thing');
  });

  it('handles destructured imports', () => {
    const { node, scope } = testItems.Destructured2;
    const itemName = node.name.name;
    const sourceModule = getSourceModuleForItem(itemName, scope);

    expect(sourceModule).not.toBeNull();
//.........這裏部分代碼省略.........
開發者ID:petehunt,項目名稱:jsxstyle,代碼行數:101,代碼來源:getSourceModule.spec.ts

示例7: Identifier

    Identifier(path) {
        console.log("Visiting: " + path.node.name);
    }
};

// Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-traverse
const code = `function square(n) {
    return n * n;
}`;

const ast = parse(code);

traverse(ast, {
    enter(path) {
        const node = path.node;
        if (t.isIdentifier(node) && node.name === "n") {
            node.name = "x";
        }
    }
});

// Examples from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#writing-your-first-babel-plugin

const v1: Visitor = {
    BinaryExpression(path) {
        if (t.isIdentifier(path.node.left)) {
            // ...
        }
        path.replaceWith(
            t.binaryExpression("**", path.node.left, t.numericLiteral(2))
        );
        path.parentPath.replaceWith(
開發者ID:AlexGalays,項目名稱:DefinitelyTyped,代碼行數:32,代碼來源:babel__traverse-tests.ts

示例8: outerFunction

describe('getStaticBindingsForScope', () => {
  const ast = parse(`
const outerLiteral = 42;
const outerObject = {
  value: 69 * 420,
};

import LC from './LC';
import { blue } from './LC';
import { Inline, Block } from 'jsxstyle';

function outerFunction(innerParam1, innerParam2) {
  const innerLiteral = 'wow';
  const innerObject = {};
  const nullLiteral = null;

  <Inline />;

  return <Block
    prop1={innerLiteral}
    prop2={LC.staticValue}
    prop3={outerLiteral}
  />;
}
`);

  const testItems: Record<
    string,
    { attrs: Record<string, any>; scope: any }
  > = {};
  traverse(ast, {
    JSXElement(traversePath) {
      const node = traversePath.node.openingElement;
      const nodeName = node.name;
      if (!t.isJSXIdentifier(nodeName)) {
        throw new Error(
          'Received invalid node name: ' + generate(node.name).code
        );
      }
      testItems[nodeName.name] = {
        attrs: {},
        scope: traversePath.scope,
      };

      node.attributes.forEach(attr => {
        if (
          !t.isJSXAttribute(attr) ||
          typeof attr.name.name !== 'string' ||
          !t.isJSXExpressionContainer(attr.value)
        ) {
          throw new Error(
            'Received invalid JSXAttribute: ' + generate(attr).code
          );
        }
        testItems[nodeName.name].attrs[attr.name.name] = attr.value.expression;
      });
    },
  });

  it('traverses the source correctly', () => {
    expect(Object.keys(testItems)).toEqual(['Inline', 'Block']);
    expect(Object.keys(testItems.Block.attrs)).toEqual([
      'prop1',
      'prop2',
      'prop3',
    ]);
  });

  it('extracts static bindings and utilises the cache', () => {
    const bindingCache = {};
    const setFn = jest.fn();
    const getFn = jest.fn();
    const thingsToSet = [];
    const thingsToGet = [];
    const proxiedCache = new Proxy(bindingCache, {
      set(target, name, value) {
        setFn();
        thingsToSet.push(name);
        return Reflect.set(target, name, value);
      },
      getOwnPropertyDescriptor(target, name) {
        getFn();
        thingsToGet.push(name);
        return Reflect.getOwnPropertyDescriptor(target, name);
      },
    });

    const blockBindings = getStaticBindingsForScope(
      testItems.Block.scope,
      whitelistedModules,
      path.resolve(__dirname, 'mock', 'demo.js'),
      proxiedCache
    );

    expect(blockBindings).toEqual({
      blue: 'blueberry',
      innerLiteral: 'wow',
      LC: require('./mock/LC'),
      nullLiteral: null,
      outerLiteral: 42,
//.........這裏部分代碼省略.........
開發者ID:petehunt,項目名稱:jsxstyle,代碼行數:101,代碼來源:getStaticBindingsForScope.spec.ts


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