首页 > 解决方案 > 如何验证打字稿文件是否包含带有正则表达式的装饰器?

问题描述

我想检查打字稿文件是否包含修饰函数或类而不编译它。是否有正则表达式或同样快速的东西可以检测打字稿文件是否包含修饰的类或函数?

标签: regextypescripttypescript-decorator

解决方案


您可以使用typescript parser解析文件。这将为您生成一个 AST(抽象语法树)。从生成的 AST 中,您可以检查文件中是否使用了任何装饰器。

要进一步了解这一点,您可以为此使用@typescript-eslint/parser解析器及其解析方法。

// requires ES6+
import { parse } from '@typescript-eslint/parser';

const code = '@Component({key: "value"}) class Hello {}';

const ast = parse(code);

console.log(JSON.stringify(ast));

这将为您返回以下 AST:

{
  "type": "Program",
  "body": [
    {
      "type": "ClassDeclaration",
      "id": { "type": "Identifier", "name": "Hello" },
      "body": { "type": "ClassBody", "body": [] },
      "superClass": null,
      "decorators": [
        {
          "type": "Decorator",
          "expression": {
            "type": "CallExpression",
            "callee": { "type": "Identifier", "name": "Component" },
            "arguments": [
              {
                "type": "ObjectExpression",
                "properties": [
                  {
                    "type": "Property",
                    "key": { "type": "Identifier", "name": "key" },
                    "value": {
                      "type": "Literal",
                      "value": "value",
                      "raw": "\"value\""
                    },
                    "computed": false,
                    "method": false,
                    "shorthand": false,
                    "kind": "init"
                  }
                ]
              }
            ],
            "optional": false
          }
        }
      ]
    }
  ],
  "sourceType": "script"
}

parse 函数也有多个选项,例如你可以打开 range 选项来找出装饰器在代码中的确切位置:parse(code, {range: true})


推荐阅读