How to use the @babel/traverse.default 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 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 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 zhangdaren / miniprogram-to-uniapp / src / wx2uni / jsHandle.js View on Github external
function handleJSImage(ast, file_js) {
	traverse(ast, {
		noScope: true,
		StringLiteral(path) {
			let reg = /\.(jpg|jpeg|gif|svg|png)$/;  //test时不能加/g

			//image标签,处理src路径
			var src = path.node.value;

			//这里取巧一下,如果路径不是以/开头,那么就在前面加上./
			if (!/^\//.test(src)) {
				src = "./" + src;
			}

			//忽略网络素材地址,不然会转换出错
			if (src && !utils.isURL(src) && reg.test(src)) {
				//static路径
				let staticPath = nodePath.join(global.miniprogramRoot, "static");
github zhangdaren / miniprogram-to-uniapp / src / wx2uni / js / appConverter.js View on Github external
VariableDeclaration(path) {
		const parent = path.parentPath.parent;
		if (t.isFile(parent)) {
			//将require()里的地址都处理一遍
			traverse(path.node, {
				noScope: true,
				CallExpression(path2) {
					let callee = path2.get("callee");
					let property = path2.get("property");
					if (t.isIdentifier(callee.node, { name: "require" })) {
						let arguments = path2.node.arguments;
						if (arguments && arguments.length) {
							if (t.isStringLiteral(arguments[0])) {
								let filePath = arguments[0].value;
								filePath = pathUtil.relativePath(filePath, global.miniprogramRoot, fileDir);
								path2.node.arguments[0] = t.stringLiteral(filePath);
							}
						}
					}
				},
				VariableDeclarator(path2) {
github niksy / modernizr-esm / build / source-entries.js View on Github external
async renderChunk(source, options) {
			const ast = parse(source, {
				sourceType: 'module'
			});
			traverse(ast, babelPlugin().visitor);
			traverse(ast, handleGlobalReference().visitor);
			const result = generate(ast);
			return `/** Original source code: https://github.com/Modernizr/Modernizr/blob/v${version}/src/${options.fileName} **/\n${result.code}`;
		}
	}
github cube-js / cube.js / packages / cubejs-server-core / dev / templates / AppSnippet.js View on Github external
insertAnchor(targetSource) {
    let appClass = null;
    traverse(targetSource.ast, {
      FunctionDeclaration: (path) => {
        if (path.get('id').node.name === 'App') {
          appClass = path;
        }
      }
    });
    if (!appClass) {
      return super.insertAnchor(targetSource);
    }
    return appClass;
  }
github hangxingliu / vscode-ant-design-pro / extension / parser / parse-antd-module.js View on Github external
function thenable(fileContent) {
		let ast = null;
		try {
			ast = parseCode(fileContent, filePath);
		} catch (ex) {
			log.error(`Error: parseCode from ${filePath}\n${ex.stack}`);
			return Promise.resolve(result);
		}

		traverse(ast, {
			enter(path) {
				if (result.ok) return;

				const type = path.node.type;
				if (type === 'ExportDefaultDeclaration' && path.node.declaration.type === 'ObjectExpression') {
					const { properties } = path.node.declaration;
					if (!properties || !Array.isArray(properties)) return;

					const keyValues = {};
					properties.map(it => {
						const key = _.get(it, 'key.name', '');
						if (!key) return;
						keyValues[key] = it;
					});

					if (!('namespace' in keyValues)) return;
github zhangdaren / miniprogram-to-uniapp / src / wx2uni / jsHandle.js View on Github external
function appGlobalDataFunHandle(ast) {
	traverse(ast, {
		noScope: true,
		MemberExpression(path) {
			let object = path.get('object');
			let property = path.get('property');
			if (babelUtil.isThisExpression(object, global.pagesData["app"]["thisNameList"]) && t.isIdentifier(property.node, { name: "globalData" })) {
				path.replaceWith(object);
				path.skip();
			}
		}
	});
}

@babel/traverse

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

MIT
Latest version published 20 days ago

Package Health Score

95 / 100
Full package analysis

Similar packages