Skip to content

feat(@ngtools/webpack): allow .svg files as templates #13284

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,6 @@ export function getCommonConfig(wco: WebpackConfigOptions) {
},
module: {
rules: [
{ test: /\.html$/, loader: 'raw-loader' },
{
test: /\.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)$/,
loader: 'file-loader',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import { runTargetSpec } from '@angular-devkit/architect/testing';
import { join, normalize, virtualFs } from '@angular-devkit/core';
import { tap } from 'rxjs/operators';
import { browserTargetSpec, host, outputPath } from '../utils';

describe('Browser Builder allow svg', () => {

beforeEach(done => host.initialize().toPromise().then(done, done.fail));
afterEach(done => host.restore().toPromise().then(done, done.fail));

it('works with aot',
(done) => {

const svg = `
<svg xmlns="http://www.w3.org/2000/svg">
<text x="20" y="20" font-size="20" fill="red">Hello World</text>
</svg>`;

host.writeMultipleFiles({
'./src/app/app.component.svg': svg,
'./src/app/app.component.ts': `
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.svg',
styleUrls: []
})
export class AppComponent {
title = 'app';
}
`,
});

const overrides = { aot: true };

runTargetSpec(host, browserTargetSpec, overrides).pipe(
tap((buildEvent) => expect(buildEvent.success).toBe(true)),
tap(() => {
const content = virtualFs.fileBufferToString(
host.scopedSync().read(join(outputPath, 'main.js')),
);

expect(content).toContain('":svg:svg"');
expect(host.scopedSync().exists(normalize('dist/app.component.svg')))
.toBe(false, 'should not copy app.component.svg to dist');
}),
).toPromise().then(done, done.fail);
});

});
3 changes: 2 additions & 1 deletion packages/ngtools/webpack/src/angular_compiler_plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,8 @@ export class AngularCompilerPlugin {

if (this._JitMode) {
// Replace resources in JIT.
this._transformers.push(replaceResources(isAppPath, getTypeChecker));
this._transformers.push(
replaceResources(isAppPath, getTypeChecker, this._options.directTemplateLoading));
} else {
// Remove unneeded angular decorators.
this._transformers.push(removeDecorators(isAppPath, getTypeChecker));
Expand Down
3 changes: 2 additions & 1 deletion packages/ngtools/webpack/src/compiler_host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,8 @@ export class WebpackCompilerHost implements ts.CompilerHost {
}

readResource(fileName: string) {
if (this.directTemplateLoading && fileName.endsWith('.html')) {
if (this.directTemplateLoading &&
(fileName.endsWith('.html') || fileName.endsWith('.svg'))) {
return this.readFile(fileName);
}

Expand Down
22 changes: 14 additions & 8 deletions packages/ngtools/webpack/src/transformers/replace_resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import * as ts from 'typescript';
export function replaceResources(
shouldTransform: (fileName: string) => boolean,
getTypeChecker: () => ts.TypeChecker,
directTemplateLoading = false,
): ts.TransformerFactory<ts.SourceFile> {

return (context: ts.TransformationContext) => {
Expand All @@ -19,7 +20,7 @@ export function replaceResources(
if (ts.isClassDeclaration(node)) {
node.decorators = ts.visitNodes(
node.decorators,
(node: ts.Decorator) => visitDecorator(node, typeChecker),
(node: ts.Decorator) => visitDecorator(node, typeChecker, directTemplateLoading),
);
}

Expand All @@ -34,7 +35,10 @@ export function replaceResources(
};
}

function visitDecorator(node: ts.Decorator, typeChecker: ts.TypeChecker): ts.Decorator {
function visitDecorator(
node: ts.Decorator,
typeChecker: ts.TypeChecker,
directTemplateLoading: boolean): ts.Decorator {
if (!isComponentDecorator(node, typeChecker)) {
return node;
}
Expand All @@ -56,7 +60,8 @@ function visitDecorator(node: ts.Decorator, typeChecker: ts.TypeChecker): ts.Dec
// visit all properties
let properties = ts.visitNodes(
objectExpression.properties,
(node: ts.ObjectLiteralElementLike) => visitComponentMetadata(node, styleReplacements),
(node: ts.ObjectLiteralElementLike) =>
visitComponentMetadata(node, styleReplacements, directTemplateLoading),
);

// replace properties with updated properties
Expand All @@ -83,6 +88,7 @@ function visitDecorator(node: ts.Decorator, typeChecker: ts.TypeChecker): ts.Dec
function visitComponentMetadata(
node: ts.ObjectLiteralElementLike,
styleReplacements: ts.Expression[],
directTemplateLoading: boolean,
): ts.ObjectLiteralElementLike | undefined {
if (!ts.isPropertyAssignment(node) || ts.isComputedPropertyName(node.name)) {
return node;
Expand All @@ -98,7 +104,7 @@ function visitComponentMetadata(
return ts.updatePropertyAssignment(
node,
ts.createIdentifier('template'),
createRequireExpression(node.initializer),
createRequireExpression(node.initializer, directTemplateLoading ? '!raw-loader!' : ''),
);

case 'styles':
Expand Down Expand Up @@ -133,13 +139,13 @@ function visitComponentMetadata(
}
}

export function getResourceUrl(node: ts.Expression): string | null {
export function getResourceUrl(node: ts.Expression, loader = ''): string | null {
// only analyze strings
if (!ts.isStringLiteral(node) && !ts.isNoSubstitutionTemplateLiteral(node)) {
return null;
}

return `${/^\.?\.\//.test(node.text) ? '' : './'}${node.text}`;
return `${loader}${/^\.?\.\//.test(node.text) ? '' : './'}${node.text}`;
}

function isComponentDecorator(node: ts.Node, typeChecker: ts.TypeChecker): node is ts.Decorator {
Expand All @@ -155,8 +161,8 @@ function isComponentDecorator(node: ts.Node, typeChecker: ts.TypeChecker): node
return false;
}

function createRequireExpression(node: ts.Expression): ts.Expression {
const url = getResourceUrl(node);
function createRequireExpression(node: ts.Expression, loader = ''): ts.Expression {
const url = getResourceUrl(node, loader);
if (!url) {
return node;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ import { tags } from '@angular-devkit/core'; // tslint:disable-line:no-implicit
import { createTypescriptContext, transformTypescript } from './ast_helpers';
import { replaceResources } from './replace_resources';

function transform(input: string, shouldTransform = true) {
function transform(input: string, shouldTransform = true, directTemplateLoading = true) {
const { program } = createTypescriptContext(input);
const getTypeChecker = () => program.getTypeChecker();
const transformer = replaceResources(() => shouldTransform, getTypeChecker);
const transformer = replaceResources(
() => shouldTransform, getTypeChecker, directTemplateLoading);

return transformTypescript(input, [transformer]);
}
Expand Down Expand Up @@ -45,7 +46,7 @@ describe('@ngtools/webpack transformers', () => {
AppComponent = tslib_1.__decorate([
Component({
selector: 'app-root',
template: require("./app.component.html"),
template: require("!raw-loader!./app.component.html"),
styles: [require("./app.component.css"), require("./app.component.2.css")]
})
], AppComponent);
Expand All @@ -56,6 +57,75 @@ describe('@ngtools/webpack transformers', () => {
expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`);
});

it('should not replace resources when directTemplateLoading is false', () => {
const input = tags.stripIndent`
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css', './app.component.2.css']
})
export class AppComponent {
title = 'app';
}
`;
const output = tags.stripIndent`
import * as tslib_1 from "tslib";
import { Component } from '@angular/core';
let AppComponent = class AppComponent {
constructor() {
this.title = 'app';
}
};
AppComponent = tslib_1.__decorate([
Component({
selector: 'app-root',
template: require("./app.component.html"),
styles: [require("./app.component.css"), require("./app.component.2.css")]
})
], AppComponent);
export { AppComponent };
`;

const result = transform(input, true, false);
expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`);
});


it('should should support svg as templates', () => {
const input = tags.stripIndent`
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.svg'
})
export class AppComponent {
title = 'app';
}
`;
const output = tags.stripIndent`
import * as tslib_1 from "tslib";
import { Component } from '@angular/core';
let AppComponent = class AppComponent {
constructor() {
this.title = 'app';
}
};
AppComponent = tslib_1.__decorate([
Component({
selector: 'app-root',
template: require("!raw-loader!./app.component.svg")
})
], AppComponent);
export { AppComponent };
`;

const result = transform(input);
expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`);
});

it('should merge styleUrls with styles', () => {
const input = tags.stripIndent`
import { Component } from '@angular/core';
Expand All @@ -81,7 +151,7 @@ describe('@ngtools/webpack transformers', () => {
AppComponent = tslib_1.__decorate([
Component({
selector: 'app-root',
template: require("./app.component.html"),
template: require("!raw-loader!./app.component.html"),
styles: ["a { color: red }", require("./app.component.css")]
})
], AppComponent);
Expand Down Expand Up @@ -116,7 +186,7 @@ describe('@ngtools/webpack transformers', () => {
AppComponent = tslib_1.__decorate([
Component({
selector: 'app-root',
template: require("./app.component.html"),
template: require("!raw-loader!./app.component.html"),
styles: [require("./app.component.css"), require("./app.component.2.css")]
})
], AppComponent);
Expand Down Expand Up @@ -151,7 +221,7 @@ describe('@ngtools/webpack transformers', () => {
AppComponent = tslib_1.__decorate([
NgComponent({
selector: 'app-root',
template: require("./app.component.html"),
template: require("!raw-loader!./app.component.html"),
styles: [require("./app.component.css"), require("./app.component.2.css")]
})
], AppComponent);
Expand All @@ -160,7 +230,7 @@ describe('@ngtools/webpack transformers', () => {

const { program } = createTypescriptContext(input);
const getTypeChecker = () => program.getTypeChecker();
const transformer = replaceResources(() => true, getTypeChecker);
const transformer = replaceResources(() => true, getTypeChecker, true);
const result = transformTypescript(input, [transformer]);

expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`);
Expand Down Expand Up @@ -190,7 +260,7 @@ describe('@ngtools/webpack transformers', () => {
AppComponent = tslib_1.__decorate([
ng.Component({
selector: 'app-root',
template: require("./app.component.html"),
template: require("!raw-loader!./app.component.html"),
styles: [require("./app.component.css"), require("./app.component.2.css")]
})
], AppComponent);
Expand Down Expand Up @@ -238,7 +308,7 @@ describe('@ngtools/webpack transformers', () => {
AppComponent = tslib_1.__decorate([
Component({
selector: 'app-root',
template: require("./app.component.html"),
template: require("!raw-loader!./app.component.html"),
styles: [require("./app.component.css")]
})
], AppComponent);
Expand Down