|
1 | | -import { path, knownFolders, File } from "tns-core-modules/file-system"; |
2 | 1 | import { ResourceLoader } from "@angular/compiler"; |
| 2 | +import { File, knownFolders, path } from "tns-core-modules/file-system"; |
| 3 | + |
| 4 | +const extensionsFallbacks = [ |
| 5 | + [".scss", ".css"], |
| 6 | + [".sass", ".css"], |
| 7 | + [".less", ".css"] |
| 8 | +]; |
3 | 9 |
|
4 | 10 | export class FileSystemResourceLoader extends ResourceLoader { |
5 | | - resolve(url: string, baseUrl: string): string { |
6 | | - // Angular assembles absolute URL's and prefixes them with // |
| 11 | + get(url: string): Promise<string> { |
| 12 | + const resolvedPath = this.resolve(url); |
| 13 | + |
| 14 | + const templateFile = File.fromPath(resolvedPath); |
| 15 | + |
| 16 | + return templateFile.readText(); |
| 17 | + } |
| 18 | + |
| 19 | + private handleAbsoluteUrls(url: string): string { |
| 20 | + // Angular assembles absolute URLs and prefixes them with // |
7 | 21 | if (url.indexOf("/") !== 0) { |
8 | | - // Resolve relative URL's based on the app root. |
9 | | - return path.join(baseUrl, url); |
| 22 | + // Resolve relative URLs based on the app root. |
| 23 | + return path.join(knownFolders.currentApp().path, url); |
10 | 24 | } else { |
11 | 25 | return url; |
12 | 26 | } |
13 | 27 | } |
14 | 28 |
|
15 | | - get(url: string): Promise<string> { |
16 | | - const appDir = knownFolders.currentApp().path; |
17 | | - const templatePath = this.resolve(url, appDir); |
| 29 | + private resolve(url: string) { |
| 30 | + const normalizedUrl = this.handleAbsoluteUrls(url); |
18 | 31 |
|
19 | | - if (!File.exists(templatePath)) { |
20 | | - throw new Error(`File ${templatePath} does not exist. Resolved from: ${url}.`); |
| 32 | + if (File.exists(normalizedUrl)) { |
| 33 | + return normalizedUrl; |
21 | 34 | } |
22 | | - let templateFile = File.fromPath(templatePath); |
23 | | - return templateFile.readText(); |
| 35 | + |
| 36 | + const fallbackCandidates = []; |
| 37 | + extensionsFallbacks.forEach(([extension, fallback]) => { |
| 38 | + if (normalizedUrl.endsWith(extension)) { |
| 39 | + fallbackCandidates.push(normalizedUrl.substr(0, normalizedUrl.length - extension.length) + fallback); |
| 40 | + } |
| 41 | + }); |
| 42 | + |
| 43 | + for (let i = 0; i < fallbackCandidates.length; i++) { |
| 44 | + if (File.exists(fallbackCandidates[i])) { |
| 45 | + return fallbackCandidates[i]; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + throw new Error(`Could not resolve ${url}. Looked for: ${normalizedUrl}, ${fallbackCandidates}`); |
24 | 50 | } |
25 | 51 | } |
0 commit comments