Skip to content

Commit 6ad80a4

Browse files
author
vakrilov
committed
feat(styling): Allow loading .css files as a fallback if no .scss file is found(#954)
1 parent fe672d2 commit 6ad80a4

File tree

1 file changed

+38
-12
lines changed

1 file changed

+38
-12
lines changed

Diff for: nativescript-angular/resource-loader.ts

+38-12
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,51 @@
1-
import { path, knownFolders, File } from "tns-core-modules/file-system";
21
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+
];
39

410
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 //
721
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);
1024
} else {
1125
return url;
1226
}
1327
}
1428

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);
1831

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;
2134
}
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}`);
2450
}
2551
}

0 commit comments

Comments
 (0)