ngx-unused
Version:
Detect unused classes (components, pipes, services and directives) defined in Angular workspace.
47 lines (46 loc) • 1.99 kB
JavaScript
import { existsSync, readFileSync } from 'fs';
import { parse } from 'node-html-parser';
import { dirname, join, resolve } from 'path';
import { getPropertyFromDecoratorCall } from './getPropertyFromDecorator.js';
export class TemplateService {
constructor(componentDecorators) {
this.templates = componentDecorators.map(decorator => this.getTemplateHtmlFromDecorator(decorator));
}
matchesSelectors(selectors) {
return this.templates.some(template => this.templateMatchesSelectors(template, selectors));
}
templateMatchesSelectors(template, selectors) {
const root = parse(template);
const normalizeSelectors = selectors.flatMap(selector => {
const withParensEscaped = selector
.replace(/^\[/, '[\\[')
.replace(/]$/, '\\]]')
.trim();
return [withParensEscaped, selector.trim()];
});
return normalizeSelectors.some(selector => {
return root.querySelectorAll(selector).length > 0;
});
}
getTemplateHtmlFromDecorator(decorator) {
const templateString = getPropertyFromDecoratorCall(decorator, 'template');
if (templateString) {
return templateString;
}
const templateUrl = getPropertyFromDecoratorCall(decorator, 'templateUrl');
if (templateUrl) {
return this.getTemplateFromFile(decorator.getSourceFile().getFilePath(), templateUrl);
}
return '';
}
getTemplateFromFile(decoratorSourceFilePath, templateUrl) {
const templateFilePath = resolve(join(dirname(decoratorSourceFilePath), templateUrl));
return existsSync(templateFilePath)
? readFileSync(templateFilePath, { encoding: 'utf-8' })
: '';
}
matchesPipeName(name) {
const pipeSelectorRegexp = new RegExp(`\\|\\s*${name}\\b`, 'gm');
return this.templates.some(template => pipeSelectorRegexp.test(template));
}
}