regex - 如何验证打字稿文件是否包含带有正则表达式的装饰器?
问题描述
我想检查打字稿文件是否包含修饰函数或类而不编译它。是否有正则表达式或同样快速的东西可以检测打字稿文件是否包含修饰的类或函数?
解决方案
您可以使用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})
推荐阅读
- c++ - boost::hana: 为什么我不能过滤一个集合?
- angular - Ionic 4 / Angular 6:选项卡中的嵌套子路由
- android - Flutter - 在地图中打开位置
- php - BadMethodCallException 调用未定义的方法 App\registeration::register() 错误
- c# - UI不更新在foreach循环C#WPF中首先播放的声音
- javascript - 反应路由器问题在需要时获取数据
- apache-flex - Flash Builder:调试与发布差异?
- javascript - 从不同范围访问函数 - 原生 js
- magento-1.9 - Magento 1.9 观察者检查客户是否至少有完整状态的订单
- python - Python locust 在 AWS 实例中不起作用