Angular Python script to find non-standalone components
This script will find all Angular components in a specified directory that are not declared as standalone: true
components. It does this by searching for TypeScript files and checking their content for the presence of the @Component
decorator without the standalone: true
flag.
Run it with your project’s root directory as argument
import os
import re
import argparse
def find_ts_files(root):
for dirpath, dirnames, filenames in os.walk(root):
# Exclude node_modules from search
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='Find Angular components not declared as standalone')
parser.add_argument('projectdir', type=str, nargs='?', default='.', help='Project directory (src will be appended)')
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()
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow