How to use babel-traverse - 10 common examples

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 bradtraversy / youtube_es2015_source / 01_babel / node_modules / babel-plugin-transform-es2015-classes / lib / vanilla.js View on Github external
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var buildDerivedConstructor = /*istanbul ignore next*/(0, _babelTemplate2.default)( /*istanbul ignore next*/"\n  (function () {\n    super(...arguments);\n  })\n"); /* eslint max-len: 0 */

var noMethodVisitor = { /*istanbul ignore next*/
  "FunctionExpression|FunctionDeclaration": function FunctionExpressionFunctionDeclaration(path) {
    if (!path.is("shadow")) {
      path.skip();
    }
  },
  /*istanbul ignore next*/Method: function Method(path) {
    path.skip();
  }
};

var verifyConstructorVisitor = /*istanbul ignore next*/_babelTraverse.visitors.merge([noMethodVisitor, { /*istanbul ignore next*/
  Super: function Super(path) {
    if (this.isDerived && !this.hasBareSuper && !path.parentPath.isCallExpression({ callee: path.node })) {
      throw path.buildCodeFrameError("'super.*' is not allowed before super()");
    }
  },


  CallExpression: { /*istanbul ignore next*/
    exit: function exit(path) {
      if (path.get("callee").isSuper()) {
        this.hasBareSuper = true;

        if (!this.isDerived) {
          throw path.buildCodeFrameError("super() is only allowed in a derived constructor");
        }
      }
github node-cube / cube / lib / cube / ext_api_process.js View on Github external
try {
      ast = babylon.parse(code, {
        // sourceType: 'module',
        filename: filepath
      });
    } catch (e) {
      e.code = 'Js_Parse_Error';
      e.file = filepath;
      e.line = e.lineNumber;
      return callback(e);
    }
    debug('parse ast ok', filepath);
    let wait = 0;
    let traverseFlag = false;
    //////////////////// walker start //////////////////////
    babelTraverse(ast, {
      CallExpression: {
        enter: function (nodePath) {
          let node = nodePath.node;
          let scope = nodePath.scope;
          // filter other property calls, like `require[test]();`, `require.resolve()`
          if (!babelType.isIdentifier(node.callee)) {
            return;
          }

          let callFuncName = node.callee.name;
          // filter other calls
          if (callFuncName !== 'require' && callFuncName !== 'load') {
            return;
          }

          let methodOverride = false;
github vicwang163 / react-to-vue / src / index.js View on Github external
})
    }
  })
  // traverse module
  let result = {
    "import": [],
    "declaration": [],
    "class": {},
    "functional": [],
    "propTypes": {},
    "defaultProps": {},
    // there exists incompatibility
    "caveats": [],
    "source": fileContent
  }
  babelTraverse(ast, {
    Program (path) {
      let nodeLists = path.node.body
      let classDefineCount = 0
      for (let i = 0; i < nodeLists.length; i++) {
        let node = nodeLists[i]
        let cPath = path.get(`body.${i}`)
        // get prop-types
        if (cPath.isExpressionStatement() && node.expression.type === 'AssignmentExpression') {
          let leftNode = node.expression.left
          if (leftNode.type === 'MemberExpression' && ["defaultProps", "propTypes"].includes(leftNode.property.name)) {
            let className = node.expression.left.object.name
            getProps(className, leftNode.property.name, node.expression.right, result)
          }
        } else if (cPath.isClassDeclaration()) {
          classDefineCount ++
          if (classDefineCount > 1) {
github parcel-bundler / parcel / src / visitors / dependencies.js View on Github external
function evaluateExpression(node) {
  // Wrap the node in a standalone program so we can traverse it
  node = types.file(types.program([types.expressionStatement(node)]));

  // Find the first expression and evaluate it.
  let res = null;
  traverse(node, {
    Expression(path) {
      res = path.evaluate();
      path.stop();
    }
  });

  return res;
}
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 TeamFleet / WhoCallsTheFleet / dev-output / js-source / node_modules / babel-core / lib / transformation / transformers / es6 / parameters / index.js View on Github external
var destructuring = _interopRequireWildcard(_destructuring);

var _default = require("./default");

var def = _interopRequireWildcard(_default);

var _rest = require("./rest");

var rest = _interopRequireWildcard(_rest);

var metadata = {
  group: "builtin-advanced"
};

exports.metadata = metadata;
var visitor = _babelTraverse.visitors.merge([{
  ArrowFunctionExpression: function ArrowFunctionExpression(path) {
    // default/rest visitors require access to `arguments`
    var params /*: Array*/ = path.get("params");
    for (var _iterator = params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) {
      var _ref;

      if (_isArray) {
        if (_i >= _iterator.length) break;
        _ref = _iterator[_i++];
      } else {
        _i = _iterator.next();
        if (_i.done) break;
        _ref = _i.value;
      }

      var param = _ref;
github babel / babel / packages / babel-core / src / transformation / transformers / es6 / block-scoping / index.js View on Github external
function traverseReplace(node, parent, scope, remaps) {
  if (t.isIdentifier(node)) {
    replace(node, parent, scope, remaps);
  }

  if (t.isAssignmentExpression(node)) {
    var ids = t.getBindingIdentifiers(node);
    for (var name in ids) {
      replace(ids[name], parent, scope, remaps);
    }
  }

  scope.traverse(node, replaceVisitor, remaps);
}

var letReferenceBlockVisitor = traverse.visitors.merge([{
  Function(node, parent, scope, state) {
    this.traverse(letReferenceFunctionVisitor, state);
    return this.skip();
  }
}, tdzVisitor]);

var letReferenceFunctionVisitor = traverse.visitors.merge([{
  ReferencedIdentifier(node, parent, scope, state) {
    var ref = state.letReferences[node.name];

    // not a part of our scope
    if (!ref) return;

    // this scope has a variable with the same name so it couldn't belong
    // to our let scope
    var localBinding = scope.getBindingIdentifier(node.name);