How to use babylon-walk - 10 common examples

To help you get started, we’ve selected a few babylon-walk 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 parcel-bundler / parcel / packages / transformers / js / src / JSTransformer.js View on Github external
async transform({asset, options, logger}) {
    asset.type = 'js';
    if (!asset.ast) {
      return [asset];
    }

    let ast = asset.ast;
    let code = await asset.getCode();

    // Inline environment variables
    if (!asset.env.isNode() && (ast.isDirty || ENV_RE.test(code))) {
      walk.simple(ast.program, envVisitor, {asset, env: options.env});
    }

    // Collect dependencies
    if (canHaveDependencies(code) || ast.isDirty) {
      walk.ancestor(ast.program, collectDependencies, {asset, options});
    }

    // If there's a hashbang, remove it and store it on the asset meta.
    // During packaging, if this is the entry asset, it will be prepended to the
    // packaged output.
    if (ast.program.program.interpreter != null) {
      asset.meta.interpreter = ast.program.program.interpreter.value;
      delete ast.program.program.interpreter;
    }

    if (!asset.env.isNode()) {
github parcel-bundler / parcel / packages / transformers / js / src / JSTransformer.js View on Github external
async transform({asset, options}) {
    asset.type = 'js';
    if (!asset.ast) {
      return [asset];
    }

    let ast = asset.ast;
    let code = await asset.getCode();

    // Inline environment variables
    if (!asset.env.isNode() && (ast.isDirty || ENV_RE.test(code))) {
      walk.simple(ast.program, envVisitor, {asset, env: options.env});
    }

    // Collect dependencies
    if (canHaveDependencies(code) || ast.isDirty) {
      walk.ancestor(ast.program, collectDependencies, {asset, options});
    }

    // If there's a hashbang, remove it and store it on the asset meta.
    // During packaging, if this is the entry asset, it will be prepended to the
    // packaged output.
    if (ast.program.program.interpreter != null) {
      asset.meta.interpreter = ast.program.program.interpreter.value;
      delete ast.program.program.interpreter;
    }

    if (!asset.env.isNode() || asset.filePath.includes('parcel/packages')) {
github parcel-bundler / parcel / packages / shared / scope-hoisting / src / concat.js View on Github external
function findRequires(
  bundleGraph: BundleGraph,
  asset: Asset,
  ast: mixed,
): Array {
  let result = [];
  walk.simple(ast, {
    CallExpression(node) {
      let {arguments: args, callee} = node;
      if (!t.isIdentifier(callee)) {
        return;
      }

      if (callee.name === '$parcel$require') {
        let dep = bundleGraph
          .getDependencies(asset)
          .find(dep => dep.moduleSpecifier === args[1].value);
        if (!dep) {
          throw new Error(`Could not find dep for "${args[1].value}`);
        }
        // can be undefined if AssetGraph#resolveDependency optimized
        // ("deferred") this dependency away as an unused reexport
        let resolution = bundleGraph.getDependencyResolution(dep);
github fraserxu / babel-jsxgettext / index.js View on Github external
.forEach(function (file) {
      var resolvedFilePath = path.join(process.cwd(), file)
      var src = fs.readFileSync(resolvedFilePath, 'utf8')

      try {
        var ast = babelParser.parse(src, {
          sourceType: 'module',
          plugins: ['jsx'].concat(plugins)
        })
      } catch (e) {
        console.error(`SyntaxError in ${file} (line: ${e.loc.line}, column: ${e.loc.column})`)
        process.exit(1)
      }

      walk.simple(ast.program, {
        CallExpression: function (node) {
          if (functionNames.hasOwnProperty(node.callee.name) ||
            node.callee.property && functionNames.hasOwnProperty(node.callee.property.name)) {
            var functionName = functionNames[node.callee.name] || functionNames[node.callee.property.name]
            var translate = {}

            var args = node.arguments
            for (var i = 0, l = args.length; i < l; i++) {
              var name = functionName[i]

              if (name && name !== 'count' && name !== 'domain') {
                var arg = args[i]
                var value = arg.value

                if (value) {
                  var line = node.loc.start.line
github remy / jsconsole / src / core / lib / run.js View on Github external
end: declaration.start,
        });
        changes.push({
          text: ')',
          start: declaration.end,
          end: declaration.end,
        });
      }
      if (!onlyOneDeclaration) {
        const last = node.declarations[node.declarations.length - 1];
        changes.push({ text: ')', start: last.end, end: last.end });
      }
    },
  };

  walk.simple(body, visitors);

  var last = body.body[body.body.length - 1];
  let additionalCode = null;

  if (last === undefined) {
    return {
      additionalCode,
      content,
    };
  }

  if (last.type === 'ExpressionStatement') {
    changes.push({
      text: 'return window.$_ = (',
      start: last.start,
      end: last.start,
github roman01la / html-to-react-components / lib / module.js View on Github external
function replaceChildInstances(body, childInstances, children) {
  childInstances = children.reduce((ret, name, idx) => {
    ret[name] = childInstances[idx];
    return ret;
  }, {});

  var idxs = children.reduce((ret, name) => {
    ret[name] = 0;
    return ret;
  }, {});

  walk.simple(body, {
    JSXOpeningElement(p) {
      var name = p.name.name;
      if (childInstances.hasOwnProperty(name)) {
        var publics = childInstances[name][idxs[name]].publics;

        publics.forEach(([attr, value]) => {
          p.attributes.push(t.jSXAttribute(t.jSXIdentifier(attr), value));
        });

        idxs[name]++;
      }
    }
  });

  return body;
}
github roman01la / html-to-react-components / lib / component.js View on Github external
function enrichWithPublics(body, publics, child) {
  walk.simple(body, {
    JSXOpeningElement(p) {
      if (p.name.name === child) {
        publics.forEach(([attr, value]) => {
          p.attributes.push(
            t.jSXAttribute(
              t.jSXIdentifier(attr),
              t.jSXExpressionContainer(value)
            )
          );
        });
      }
    }
  });
  return body;
}
github Kureev / react-navigation-parser / src / parser / getRoutes.js View on Github external
const visitors = {
    CallExpression(node) {
      const navigatorIndex = navigatorsList.indexOf(node.callee.name);
      if (navigatorIndex > -1) {
        navigationType = navigatorsList[navigatorIndex];
        nodes.push(node);
      }
    },
  };

  /**
   * First we walk through the file AST to find a call expression(s) that
   * creates a StackNavigator instance. (@todo Change it to all possible navigators)
   * All call expressions are collected in `nodes` array.
   */
  walk.simple(ast, visitors);

  /**
   * Once we have all call expressions in array, we can get their arguments (e.g. routes)
   * In the scope of proof of concept implementation I'll keep it simple and take only
   * the first one call expression. If it'll be needed, this code can be replaced by
   * something more generic. We also take the first argument (object / variable with routes)
   */
  const firstArg = nodes[0].arguments[0];

  /**
   * Routes can be passed as object expression or a variable. We need to handle both cases:
   */
  let routes;
  if (t.isObjectExpression(firstArg)) {
    routes = resolveObjectExpression(firstArg, ast);
  } else if (t.isIdentifier(firstArg)) {
github Kureev / react-navigation-parser / src / parser / getTransitions.js View on Github external
);

      const isCalledByMemberExpression = (
        t.isMemberExpression(callee) &&
        t.isIdentifier(callee.property) &&
        callee.property.name === 'navigate' &&
        hasNavigationSignature(args)
      );

      if (isCalledByIdentifier || isCalledByMemberExpression) {
        transitions.push(args[0].value);
      }
    },
  };

  walk.simple(ast, visitors);
  return transitions;
};
github Kureev / react-navigation-parser / src / parser / getComponentName.js View on Github external
if (t.isIdentifier(superClass)) {
        if (['PureComponent', 'Component'].indexOf(superClass.name) > -1) {
          isStatefulComponent = true;
        }
      } else if (t.isMemberExpression(superClass)) {
        if (
          superClass.object.name === 'React' &&
          superClass.property.name === 'Component'
        ) {
          isStatefulComponent = true;
        }
      }
    },
  };

  walk.simple(ast, visitors);
  const isReactComponent = importsReact && hasExport;

  if (!isReactComponent) {
    return null;
  }

  if (isStatefulComponent && t.isIdentifier(defaultExportNode)) {
    return defaultExportNode.name;
  }

  if (t.isCallExpression(defaultExportNode)) {
    if (defaultExportNode.callee.callee.name === 'connect') {
      return defaultExportNode.arguments[0].name;
    }
  }

babylon-walk

Lightweight Babylon AST traversal

MIT
Latest version published 8 years ago

Package Health Score

52 / 100
Full package analysis

Popular babylon-walk functions

Similar packages