项目作者: adammedford

项目描述 :
Query TypeScript AST with astq Query engine + TypeScript adapter
高级语言: TypeScript
项目地址: git://github.com/adammedford/astq-ts.git
创建时间: 2018-11-09T02:55:38Z
项目社区:https://github.com/adammedford/astq-ts

开源协议:MIT License

下载


astq-ts

ASTQ TypeScript adapter that enables querying TypeScript generated abstract syntax trees

Project scaffolded using typescript-library-starter

styled with prettier

About

Enables usage of ASTQ’s XPath-like syntax for querying abstract syntax trees generated by TypeScript’s createSourceFile.

Usage

  1. import * as astq from 'astq';
  2. import { ASTQAdapterTypeScript } from 'astq-ts';
  3. import * as typescript from 'typescript';
  4. export class QueryEngineWrapper {
  5. queryEngine;
  6. constructor() {
  7. this.queryEngine = new astq();
  8. // The adapter takes a reference to your typescript install in its constructor to make sure the node types match your version
  9. this.queryEngine.adapter(new ASTQAdapterTypeScript(typescript));
  10. }
  11. public querySource(tsAST: any, query: string, queryOptions?: any): any[] {
  12. return astq.query(tsAST, query, queryOptions);
  13. }
  14. }
  15. const myTree = createASTFromSource(sampleSource);
  16. const wrapper = new QueryEngineWrapper();
  17. wrapper.querySource(myTree, sampleQuery).forEach((node) => {
  18. console.log(`${node.name.escapedText}: ${node.initializer.text}`);
  19. })
  20. /**
  21. * Prints
  22. * bar: quux
  23. * baz: 42
  24. */
  25. function createASTFromSource(source: string, fileName?: string = 'test.js') {
  26. return typescript.createSourceFromFile(fileName, source, typescript.ScriptTarget.Latest, true);
  27. }
  28. const sampleSource = `
  29. class Foo {
  30. foo () {
  31. const bar = "quux"
  32. let baz = 42
  33. }
  34. }
  35. `
  36. const sampleQuery = `
  37. // VariableDeclaration [
  38. /:name Identifier [ @escapedText ]
  39. &&
  40. (/:initializer StringLiteral [ @text ] || /:initializer * [ @text ])
  41. ]
  42. `

NPM scripts

  • npm t: Run test suite
  • npm start: Run npm run build in watch mode
  • npm run test:watch: Run test suite in interactive watch mode
  • npm run test:prod: Run linting and generate coverage
  • npm run build: Generate bundles and typings, create docs
  • npm run lint: Lints code