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 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 facebook / react / scripts / print-warnings / print-warnings.js View on Github external
fs.readFile(file.path, 'utf8', function(err, source) {
    if (err) {
      cb(err);
      return;
    }

    let ast;
    try {
      ast = babylon.parse(source, babylonOptions);
    } catch (error) {
      console.error('Failed to parse source file:', file.path);
      throw error;
    }

    traverse(ast, {
      CallExpression: {
        exit: function(astPath) {
          const callee = astPath.get('callee');
          if (
            callee.matchesPattern('console.warn') ||
            callee.matchesPattern('console.error')
          ) {
            const node = astPath.node;
            if (node.callee.type !== 'MemberExpression') {
              return;
            }
            if (node.callee.property.type !== 'Identifier') {
              return;
            }
            // warning messages can be concatenated (`+`) at runtime, so here's
            // a trivial partial evaluator that interprets the literal value
github 4Catalyzer / astroturf / src / plugin.js View on Github external
});

      styles = Array.from(styles.values());

      changeset = changeset.concat(styles);

      file.metadata.astroturf = { styles, changeset };

      if (opts.writeFiles !== false) {
        styles.forEach(({ absoluteFilePath, value }) => {
          outputFileSync(absoluteFilePath, stripIndent([value]));
        });
      }
    },

    visitor: visitors.merge([
      {
        Program: {
          enter(_, state) {
            state.defaultedOptions = defaults(state.opts, {
              tagName: 'css',
              allowGlobal: true,
              styledTag: 'styled',
              customCssProperties: 'cssProp', // or: true, false
            });
          },
        },

        ImportDeclaration: {
          exit(path, state) {
            const { tagName } = state.defaultedOptions;
            const specifiers = path.get('specifiers');
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 skyFi / weapp-native / src / bin / transform.js View on Github external
}

  const css = (id) => {
    const { dir, name } = _path.parse(id)
    const cssPathname = _path.resolve(dir, `${name}.css`)
    if (fs.existsSync(cssPathname)) {
      const css = fs.readFileSync(cssPathname, 'utf-8')
      output.css = css
    }
  }

  css(id)

  const AST = parse(code)
  // traverse(AST, Object.assign({}, visitor, visitJSX, visitCSS))
  traverse(AST, Object.assign({}, visitor, visitJSX))

  // reference templates
  if (Object.keys(ImportTemplates).length) {
    output.wxml =
      Object.entries(ImportTemplates)
        .map(([, src]) => `\n`)
        .join('') + output.wxml
  }

  // .json
  const _json = isApp() || isGame() // 小程序配置
    ? ImportPages.length
      ? Object.assign({ pages: ImportPages }, JSONAttrs)
      : Object.keys(JSONAttrs).length ? JSONAttrs : undefined
    : isComponent() // 组件配置
      ? {
github dcloudio / uni-app / packages / uni-template-compiler / lib / script / traverse / index.js View on Github external
module.exports = function traverse (ast, state) {
  const identifierArray = []
  const blockStatementBody = []
  const objectPropertyArray = []
  const initExpressionStatementArray = []
  // TODO 待重构,至少 filter,method 等实现方式要调整
  babelTraverse(ast, visitor, undefined, {
    scoped: [],
    context: VAR_ROOT,
    options: state.options,
    errors: state.errors,
    tips: state.tips,
    identifierArray: identifierArray,
    propertyArray: objectPropertyArray,
    declarationArray: blockStatementBody,
    initExpressionStatementArray: initExpressionStatementArray
  })

  if (initExpressionStatementArray.length) {
    blockStatementBody.push(getInItIfStatement(initExpressionStatementArray))
  }

  if (objectPropertyArray.length) {
github parcel-bundler / parcel / packages / shared / scope-hoisting / src / hoist.js View on Github external
path.replaceWith(
          t.program([
            WRAPPER_TEMPLATE({
              NAME: getIdentifier(asset, 'exports'),
              BODY: path.node.body,
            }),
          ]),
        );

        asset.symbols.clear();
        asset.meta.isCommonJS = true;
        asset.meta.isES6Module = false;
      } else {
        // Re-crawl scope so we are sure to have all bindings.
        traverse.cache.clearScope();
        scope.crawl();

        // Rename each binding in the top-level scope to something unique.
        for (let name in scope.bindings) {
          if (!name.startsWith('$' + t.toIdentifier(asset.id))) {
            let newName = getName(asset, 'var', name);
            rename(scope, name, newName);
          }
        }

        let exportsIdentifier = getIdentifier(asset, 'exports');

        // Add variable that represents module.exports if it is referenced and not declared.
        if (
          scope.hasGlobal(exportsIdentifier.name) &&
          !scope.hasBinding(exportsIdentifier.name)
github facebook / prepack / src / react / utils.js View on Github external
if (t.isMemberExpression(parentNode)) {
              // remove the "this" from the member
              parentPath.replaceWith(parentNode.property);
            } else {
              throw new FatalError(
                `conversion of a simple class component to functional component failed due to "this" not being replaced`
              );
            }
          }
        },
      },
      undefined,
      {},
      undefined
    );
    traverse.cache.clear();
  });
}
github parcel-bundler / parcel / packages / shared / scope-hoisting / src / hoist.js View on Github external
enter(path, asset: MutableAsset) {
      asset.meta.id = asset.id;
      asset.meta.exportsIdentifier = getName(asset, 'exports');

      traverse.cache.clearScope();
      path.scope.crawl();

      let shouldWrap = false;
      path.traverse({
        CallExpression(path) {
          // If we see an `eval` call, wrap the module in a function.
          // Otherwise, local variables accessed inside the eval won't work.
          let callee = path.node.callee;
          if (
            t.isIdentifier(callee) &&
            callee.name === 'eval' &&
            !path.scope.hasBinding('eval', true)
          ) {
            asset.meta.isCommonJS = true;
            shouldWrap = true;
            path.stop();

@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