From e0178b5a97383e15112c19f4f7e81109db8c35f4 Mon Sep 17 00:00:00 2001 From: Kim Biesbjerg Date: Thu, 13 Jun 2019 12:32:18 +0200 Subject: [PATCH] (bugfix) fix unmatched selector error when template didnt contain any html --- src/parsers/directive.parser.ts | 19 ++++++++++++++++--- tests/parsers/directive.parser.spec.ts | 14 ++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/parsers/directive.parser.ts b/src/parsers/directive.parser.ts index ad0bffa..137ba6c 100644 --- a/src/parsers/directive.parser.ts +++ b/src/parsers/directive.parser.ts @@ -4,7 +4,7 @@ import { isPathAngularComponent, extractComponentInlineTemplate } from '../utils import * as cheerio from 'cheerio'; -const $ = cheerio.load('', {xmlMode: true}); +const $ = cheerio.load('', { xmlMode: true }); export class DirectiveParser implements ParserInterface { @@ -19,9 +19,9 @@ export class DirectiveParser implements ParserInterface { protected parseTemplate(template: string): TranslationCollection { let collection: TranslationCollection = new TranslationCollection(); - template = this.normalizeTemplateAttributes(template); - const selector = '[translate], [ng2-translate]'; + + template = this.prepareTemplate(template); $(template) .find(selector) .addBack(selector) @@ -45,6 +45,12 @@ export class DirectiveParser implements ParserInterface { return collection; } + protected prepareTemplate(template: string): string { + return this.wrapTemplate( + this.normalizeTemplateAttributes(template) + ); + } + /** * Angular's `[attr]="'val'"` syntax is not valid HTML, * so it can't be parsed by standard HTML parsers. @@ -54,4 +60,11 @@ export class DirectiveParser implements ParserInterface { return template.replace(/\[([^\]]+)\]="'([^']*)'"/g, '$1="$2"'); } + /** + * Wraps template in tag + */ + protected wrapTemplate(template: string, tag: string = 'div'): string { + return `<${tag}>${template}`; + } + } diff --git a/tests/parsers/directive.parser.spec.ts b/tests/parsers/directive.parser.spec.ts index b110977..b0028c0 100644 --- a/tests/parsers/directive.parser.spec.ts +++ b/tests/parsers/directive.parser.spec.ts @@ -124,4 +124,18 @@ describe('DirectiveParser', () => { expect(keys).to.deep.equal(['Hello World']); }); + it('should not cause error when no html is present in template', () => { + const contents = ` + import { Component } from '@angular/core'; + @Component({ + template: '{{ variable }}' + }) + export class MyComponent { + variable: string + } + `; + const keys = parser.extract(contents, componentFilename).keys(); + expect(keys).to.deep.equal([]); + }); + });