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 akameco / s2s / .deprecated / babel-plugin-s2s-jest-unit-test-case / src / index.js View on Github external
const getFuncNames = (code /* :string */) => {
  const ast = parse(code, {
    sourceType: 'module',
    plugins: ['flow', 'objectRestSpread'],
  })

  const names /* :string[] */ = []

  traverse(ast, {
    FunctionDeclaration(path) {
      if (!path.findParent(p => p.isExportDeclaration())) {
        return
      }
      const name = path.get('id').node.name
      names.push(name)
    },
  })

  return names
}
github linkedin / css-blocks / packages / jsx / src / analyzer / index.ts View on Github external
});
        template.data = wat.outputText;
      }

      analysis.template.ast = some(babylon.parse(template.data, this.options.parserOptions));
    } catch (e) {
      process.chdir(oldDir);
      throw new JSXParseError(`Error parsing '${template.identifier}'\n${e.message}\n\n${template.data}: ${e.message}`, { filename: template.identifier });
    }

    // The blocks importer will insert a promise that resolves to a `ResolvedBlock`
    // for each CSS Blocks import it encounters. Every new `tsx` or `jsx` file discovered
    // will kick of another `Analyzer.parse()` for that file.
    let blockPromises: Promise[] = [];
    let childTemplatePromises: Promise[] = [];
    traverse(unwrap(analysis.template.ast), importVisitor(template, this, analysis, blockPromises, childTemplatePromises, this.options));

    // Once all blocks this file is waiting for resolve, resolve with the File object.

    // After import traversal, it is safe to move back to our old working directory.
    process.chdir(oldDir);

    // Wait for all block promises to resolve then resolve with the finished analysis.
    debug(`Waiting for ${blockPromises.length} Block imported by "${template.identifier}" to finish compilation.`);
    await Promise.all(blockPromises);
    debug(`Waiting for ${childTemplatePromises.length} child templates to finish analysis before analysis of ${template.identifier}.`);
    await Promise.all(childTemplatePromises);
    debug(`All child compilations finished for "${template.identifier}".`);
    return analysis;

  }
github Polymer / tools / packages / bundler / src / es6-rewriter.ts View on Github external
babel.newExpression(
                            babel.identifier('URL'),
                            [
                              //
                              babel.stringLiteral(relativeUrl),
                              babel.memberExpression(
                                  babel.memberExpression(
                                      babel.identifier('import'),
                                      babel.identifier('meta')),
                                  babel.identifier('url'))
                            ]),
                        babel.identifier('href')))
              ]))
        ]);
    const newModuleFile = clone(moduleFile);
    traverse(newModuleFile, {
      noScope: true,
      MetaProperty: {
        enter(path: NodePath) {
          const metaProperty = path.node;
          if (metaProperty.meta.name !== 'import' &&
              metaProperty.property.name !== 'meta') {
            // We're specifically looking for instances of `import.meta` so
            // ignore any other meta properties.
            return;
          }
          const bundledImportMeta =
              babel.identifier(bundledImportMetaIdentifierName);
          path.replaceWith(bundledImportMeta);
        },
      },
    });
github ScriptedAlchemy / webpack-external-import / src / babel / index.js View on Github external
Identifier(p) {
        // only care about promise callbacks
        if (!p.isIdentifier({name: 'then'})) {
          return;
        }

        const parentPath = p.findParent((path) => path.isCallExpression());
        traverse(parentPath.node, {
          ArrowFunctionExpression(path) {
            const moduleMaps = new Set()
            if (path.isArrowFunctionExpression()) {
              if (path.node.params) {
                path.node.params.forEach(node => {
                  if (node.type === 'ObjectPattern') {
                    node.properties.forEach(property => {
                      if (!moduleMaps.has(property.key.name)) moduleMaps.add(property.key.name);
                    });
                    node.properties.length = 0;
                  }
                });
              }

              const injectedDepencency = Array.from(moduleMaps)
                .map(moduleName => {
github alibaba / rax / packages / element-loader / src / transformer.js View on Github external
type !== 'ObjectProperty' ||
          parent.key !== node
        ) &&

          !findScope(scope, node.name)

      ) {
        node.name = `props.${node.name}`;
      }
    }
  };

  let codeStr = code;

  const ast = babylon.parse(`(${codeStr})`);
  traverse(ast, visitor);
  let newCode = generate(ast).code;
  if (newCode.charAt(newCode.length - 1) === ';') {
    newCode = newCode.slice(0, -1);
  }

  return `(${newCode})`;
}
github oliviertassinari / i18n-extract / index.js View on Github external
'asyncFunctions',
      'classConstructorCall',
      'doExpressions',
      'trailingFunctionCommas',
      'objectRestSpread',
      'decorators',
      'classProperties',
      'exportExtensions',
      'exponentiationOperator',
      'asyncGenerators',
      'functionBind',
      'functionSent',
    ],
  });

  traverse(ast, {
    CallExpression(path) {
      const callee = path.node.callee;

      if (callee.type === 'Identifier' && callee.name === (options.marker || 'i18n')) {
        const message = getMessage(path.node.arguments[0]);

        if (message) {
          messages.push(message);
        }
      }
    },
  });

  return uniq(messages);
}
github NervJS / taro / packages / taro-cli / src / util / resolve_npm_files.ts View on Github external
filePath: string,
  files: string[],
  isProduction: boolean,
  npmConfig: INpmConfig,
  rootNpm: string,
  npmOutputDir: string,
  buildAdapter: BUILD_TYPES,
  compileConfig: {[k: string]: any},
  env: object,
  uglify: TogglableOptions,
  babelConfig: object,
  quickappManifest?: ITaroManifestConfig
}) {
  const excludeRequire: string[] = []

  traverse(ast, {
    IfStatement (astPath) {
      astPath.traverse({
        BinaryExpression (astPath) {
          const node = astPath.node
          const left = node.left
          const right = node.right
          if (t.isMemberExpression(left) && t.isStringLiteral(right)) {
            if (generate(left).code === 'process.env.TARO_ENV' &&
              (node.right as t.StringLiteral).value !== buildAdapter) {
              const consequentSibling = astPath.getSibling('consequent')
              consequentSibling.traverse({
                CallExpression (astPath) {
                  if (astPath.get('callee').isIdentifier({ name: 'require' })) {
                    const arg = astPath.get('arguments')[0]
                    if (t.isStringLiteral(arg.node)) {
                      excludeRequire.push(arg.node.value)
github iammerrick / react-sourcerer / modules / Match.js View on Github external
const walk = {
    enter(path) {
      const isMatch = match(path);

      if (isMatch) {
        matches.push(
          path
        );
      }
    },
  };

  if (ast) {
    ast.traverse(walk);
  } else {
    traverse(context.ast, walk);
  }

  return matches;
};
github Canner / canner / packages / canner-schema-loader / src / index.js View on Github external
function traverseAst(ast, nullPropsCallback, ObjectPropsCallback) {
  traverse(ast, {
    CallExpression(path) {
      let typeNode, propsNode, type, packageName;
      if (path.node.arguments.length < 2) {
        return;
      }
      typeNode = path.get('arguments.0');
      propsNode = path.get('arguments.1');
      if (typeNode.isStringLiteral() && propsNode.isNullLiteral()) {
        type = typeNode.node.value;
        packageName = componentMap.get('type');
        if (!packageName) {
          return;
        }
        nullPropsCallback({
          packageName,
          type,
github NervJS / taro / packages / taro-cli / src / h5 / index.ts View on Github external
let basenameNode = mountApisOptNode.properties.find((property: t.ObjectProperty) => {
                      return toVar(property.key) === 'currentPagename'
                    }) as t.ObjectProperty | undefined
                    if (basenameNode) {
                      basenameNode.value = valueNode
                    } else {
                      basenameNode = t.objectProperty(t.stringLiteral('currentPagename'), valueNode)
                      mountApisOptNode.properties.push(basenameNode)
                    }
                  }
                }
              })
            }
          }
        }
        traverse(ast, replaceMultiRouterVisitor)
        return [filePath, generateCode(ast)]
      })
    } else {