Angular:查找非 standalone 组件的 Python 脚本

此脚本会查找指定目录中所有声明为 standalone: true 的 Angular 组件。它通过搜索 TypeScript 文件并检查其内容中是否存在没有 standalone: true 标志的 @Component 装饰器来实现。

以项目根目录作为参数运行:

find_non_standalone_components.py
#!/usr/bin/env python3
import os
import re
import argparse

def find_ts_files(root):
    for dirpath, dirnames, filenames in os.walk(root):
        # 从搜索中排除 node_modules
        dirnames[:] = [d for d in dirnames if d != 'node_modules']
        for filename in filenames:
            if filename.endswith('.ts'):
                yield os.path.join(dirpath, filename)

def is_non_standalone_component(filepath):
    with open(filepath, encoding='utf-8') as f:
        content = f.read()
        if re.search(r'@Component\s*\(', content):
            if not re.search(r'standalone\s*:\s*true', content):
                return True
    return False

def main():
    parser = argparse.ArgumentParser(description='查找未声明为 standalone 的 Angular 组件')
    parser.add_argument('projectdir', type=str, nargs='?', default='.', help='项目目录(将追加 src)')
    args = parser.parse_args()
    src_dir = os.path.join(args.projectdir, 'src')
    non_standalone = []
    for ts_file in find_ts_files(src_dir):
        if is_non_standalone_component(ts_file):
            non_standalone.append(ts_file)
    if non_standalone:
        print('Components not declared as standalone:')
        for f in non_standalone:
            print(f)
    else:
        print('All components are standalone.')

if __name__ == '__main__':
    main()

Check out similar posts by category: Angular, Python