How to use the @babel/traverse function in @babel/traverse

To help you get started, we’ve selected a few @babel/traverse 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 jsxstyle / jsxstyle / packages / jsxstyle-prettier-parser / src / babylonTraverse.ts View on Github external
} catch (e) {
            console.error(e);
            return;
          }
        }

        attr.value = t.stringLiteral(seenValues[attr.value.value]);
        // TODO: figure out a better way to set the raw value
        (attr.value as any).raw = JSON.stringify(seenValues[attr.value.value]);
      });

      return null;
    },
  };

  traverse(ast, traverseOptions);
}
github umijs / umi / packages / umi-build-dev / src / utils / writeNewRoute.js View on Github external
export function getNewRouteCode(configPath, newRoute, absSrcPath) {
  debug(`find routes in configPath: ${configPath}`);
  const ast = parser.parse(readFileSync(configPath, 'utf-8'), {
    sourceType: 'module',
    plugins: ['typescript'],
  });
  let routesNode = null;
  const importModules = [];
  // 查询当前配置文件是否导出 routes 属性
  traverse(ast, {
    Program({ node }) {
      // find import
      const { body } = node;
      body.forEach(item => {
        if (t.isImportDeclaration(item)) {
          const { specifiers } = item;
          const defaultEpecifier = specifiers.find(s => {
            return t.isImportDefaultSpecifier(s) && t.isIdentifier(s.local);
          });
          if (defaultEpecifier && t.isStringLiteral(item.source)) {
            importModules.push({
              identifierName: defaultEpecifier.local.name,
              modulePath: item.source.value,
            });
          }
        }
github umijs / umi / packages / umi-build-dev / src / plugins / commands / config / setConfig.js View on Github external
export function update(content, key, value) {
  const ast = parser.parse(content, {
    sourceType: 'module',
    plugins: ['jsx', 'typescript'],
  });
  traverse(ast, {
    ExportDefaultDeclaration(path) {
      let node = path.node.declaration;

      // export default {} as IConfig;
      if (node.type === 'TSAsExpression') {
        node = node.expression;
      }

      // const a;
      // export default a;
      if (t.isIdentifier(node) && path.scope.hasBinding(node.name)) {
        const bindingNode = path.scope.getBinding(node.name).path.node;
        if (t.isVariableDeclarator(bindingNode)) {
          node = bindingNode.init;
        }
      }
github azu / power-doctest / packages / comment-to-assert / src / comment-to-assert.ts View on Github external
export function toAssertFromAST(ast: T, options: wrapAssertOptions = {}): T {
    const replaceSet = new Set();
    let id = 0;
    traverse(ast, {
        exit(path) {
            if (!replaceSet.has(path.node) && path.node.trailingComments) {
                const commentExpression = tryGetCodeFromComments(path.node.trailingComments);
                if (commentExpression) {
                    const commentExpressionNode = getExpressionNodeFromCommentValue(commentExpression);
                    const actualNode = isExpressionStatement(path.node) ? path.node.expression : path.node;
                    const replacement = wrapAssert(
                        {
                            actualNode: actualNode,
                            expectedNode: commentExpressionNode,
                            commentExpression,
                            id: String(`id:${id++}`)
                        },
                        options
                    );
                    if (Array.isArray(replacement)) {
github jsxstyle / jsxstyle / tests / jsxstyle-webpack-plugin / getSourceModule.spec.ts View on Github external
const {Original: Reassigned1} = require('reassigned');

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

;
;
;
;
;
;
`);

  const testItems: Record = {};
  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', () => {
github Raathigesh / fabulous / src / extension / file-handlers / ts.ts View on Github external
export function getClassDeclarationStrings(ast: any) {
  const results: StyleExpressions[] = [];
  traverse(ast, {
    ClassDeclaration(path: any) {
      try {
        const stylesNode = path.node.decorators[0].expression.arguments[0].properties.find((prop: any) => prop.key.name === 'styles');
        if (stylesNode && stylesNode.value.elements.length > 0) {
          const cssString = stylesNode.value.elements[0].quasis[0].value.raw;
          const location = stylesNode.value.elements[0].quasis[0].loc;

          results.push({
            name: path.node.id.name,
            cssString: cssString,
            location: {
              start: {
                column: (location.start && location.start.column) || 0,
                line: (location.start && location.start.line - 1) || 0,
              },
              end: {
github parcel-bundler / parcel / packages / shared / scope-hoisting / src / hoist.js View on Github external
export function hoist(asset: MutableAsset) {
  if (
    !asset.ast ||
    asset.ast.type !== 'babel' ||
    asset.ast.version !== '7.0.0'
  ) {
    throw new Error('Asset does not have a babel AST');
  }

  asset.ast.isDirty = true;
  traverse(asset.ast.program, VISITOR, null, asset);
}
github wix / vscode-glean / src / parsing.ts View on Github external
export function getIdentifier(code) {
    const identifiers = [];
    const Visitor = {
        Identifier(path) {
            if ((t.isProgram(path.parentPath.parent) || t.isFile(path.parentPath.parent) || t.isExportDeclaration(path.parentPath.parent)) && path.listKey !== 'params' && path.key !== 'superClass') {
                identifiers.push(path.node.name);
            }
        }
    };

    traverse(codeToAst(code), Visitor);

    return identifiers;
}

@babel/traverse

The Babel Traverse module maintains the overall tree state, and is responsible for replacing, removing, and adding nodes

MIT
Latest version published 26 days ago

Package Health Score

95 / 100
Full package analysis