Skip to content

Commit

Permalink
fix(@angular-devkit/build-angular): handle HTML file with no body and…
Browse files Browse the repository at this point in the history
… head tags

Closes #19426
  • Loading branch information
alan-agius4 authored and filipesilva committed Nov 20, 2020
1 parent 0b06fd6 commit 9908b59
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
Expand Up @@ -87,7 +87,7 @@ export async function augmentIndexHtml(params: AugmentIndexHtmlOptions): Promise
}
}

const scriptTags: string[] = [];
let scriptTags: string[] = [];
for (const script of scripts) {
const attrs = [`src="${deployUrl}${script}"`];

Expand Down Expand Up @@ -124,7 +124,7 @@ export async function augmentIndexHtml(params: AugmentIndexHtmlOptions): Promise
scriptTags.push(`<script ${attrs.join(' ')}></script>`);
}

const linkTags: string[] = [];
let linkTags: string[] = [];
for (const stylesheet of stylesheets) {
const attrs = [
`rel="stylesheet"`,
Expand Down Expand Up @@ -180,19 +180,30 @@ export async function augmentIndexHtml(params: AugmentIndexHtmlOptions): Promise
for (const linkTag of linkTags) {
rewriter.emitRaw(linkTag);
}

linkTags = [];
break;
case 'body':
// Add script tags
for (const scriptTag of scriptTags) {
rewriter.emitRaw(scriptTag);
}

scriptTags = [];
break;
}

rewriter.emitEndTag(tag);
});

return transformedContent;
const content = await transformedContent;

if (linkTags.length || scriptTags.length) {
// In case no body/head tags are not present (dotnet partial templates)
return linkTags.join('') + scriptTags.join('') + content;
}

return content;
}

function generateSriAttributes(content: string): string {
Expand Down
Expand Up @@ -166,4 +166,27 @@ describe('augment-index-html', () => {
</html>
`);
});

it(`should add script and link tags even when body and head element doesn't exist`, async () => {
const source = augmentIndexHtml({
...indexGeneratorOptions,
html: `<app-root></app-root>`,
files: [
{ file: 'styles.css', extension: '.css', name: 'styles' },
{ file: 'runtime.js', extension: '.js', name: 'main' },
{ file: 'main.js', extension: '.js', name: 'main' },
{ file: 'runtime.js', extension: '.js', name: 'polyfills' },
{ file: 'polyfills.js', extension: '.js', name: 'polyfills' },
],
});

const html = await source;
expect(html).toEqual(oneLineHtml`
<link rel="stylesheet" href="styles.css">
<script src="runtime.js" defer></script>
<script src="polyfills.js" defer></script>
<script src="main.js" defer></script>
<app-root></app-root>
`);
});
});

0 comments on commit 9908b59

Please sign in to comment.