Files
angular/packages/compiler-cli/src/ngtsc/resource_loader.ts
Alex Rickabaugh 0c3738a780 feat(ivy): support templateUrl for ngtsc (#24704)
This commit adds support for templateUrl in component templates within
ngtsc. The compilation pipeline is split into sync and async versions,
where asynchronous compilation invokes a special preanalyze() phase of
analysis. The preanalyze() phase can optionally return a Promise which
will delay compilation until it resolves.

A ResourceLoader interface is used to resolve templateUrls to template
strings and can return results either synchronously or asynchronously.
During sync compilation it is an error if the ResourceLoader returns a
Promise.

Two ResourceLoader implementations are provided. One uses 'fs' to read
resources directly from disk and is chosen if the CompilerHost doesn't
provide a readResource method. The other wraps the readResource method
from CompilerHost if it's provided.

PR Close #24704
2018-07-03 13:31:44 -07:00

60 lines
1.5 KiB
TypeScript

/**
* @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 * as fs from 'fs';
import {ResourceLoader} from './annotations';
/**
* `ResourceLoader` which delegates to a `CompilerHost` resource loading method.
*/
export class HostResourceLoader implements ResourceLoader {
private cache = new Map<string, string>();
private fetching = new Set<string>();
constructor(private host: (url: string) => string | Promise<string>) {}
preload(url: string): Promise<void>|undefined {
if (this.cache.has(url) || this.fetching.has(url)) {
return undefined;
}
const result = this.host(url);
if (typeof result === 'string') {
this.cache.set(url, result);
return undefined;
} else {
this.fetching.add(url);
return result.then(str => {
this.fetching.delete(url);
this.cache.set(url, str);
});
}
}
load(url: string): string {
if (this.cache.has(url)) {
return this.cache.get(url) !;
}
const result = this.host(url);
if (typeof result !== 'string') {
throw new Error(`HostResourceLoader: host(${url}) returned a Promise`);
}
this.cache.set(url, result);
return result;
}
}
/**
* `ResourceLoader` which directly uses the filesystem to resolve resources synchronously.
*/
export class FileResourceLoader implements ResourceLoader {
load(url: string): string { return fs.readFileSync(url, 'utf8'); }
}