-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.ts
188 lines (165 loc) · 5.08 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { Plugin } from "esbuild";
import { CssNode } from "css-tree";
import {
compilePatterns,
isExternal,
WildcardPattern,
} from "./internals/external";
import fs = require("fs-extra");
import sass = require("sass");
import tmp = require("tmp");
import path = require("path");
import csstree = require("css-tree");
import url = require("url");
type SassOptions = Omit<sass.Options<"sync">, "file">;
interface Options {
rootDir?: string;
customSassOptions?: SassOptions;
}
export = (options: Options = {}): Plugin => ({
name: "sass",
setup: function (build) {
const { rootDir = process.cwd(), customSassOptions = {} } = options;
const { external = [] } = build.initialOptions;
const tmpDirPath = tmp.dirSync().name;
build.onResolve(
{ filter: /.\.(scss|sass)$/, namespace: "file" },
async (args) => {
const sourceFullPath = require.resolve(args.path, {
paths: [args.resolveDir],
});
const sourceExt = path.extname(sourceFullPath);
const sourceBaseName = path.basename(sourceFullPath, sourceExt);
const sourceDir = path.dirname(sourceFullPath);
const sourceRelDir = path.relative(path.dirname(rootDir), sourceDir);
const tmpDir = path.resolve(tmpDirPath, sourceRelDir);
const tmpFilePath = path.resolve(tmpDir, `${sourceBaseName}.css`);
await fs.ensureDir(tmpDir);
// Compile SASS to CSS
const sassRenderResult = await sass.compile(
sourceFullPath,
customSassOptions
);
let css = sassRenderResult.css.toString();
// Replace all relative urls
css = await replaceUrls(
css,
tmpFilePath,
sourceDir,
rootDir,
compilePatterns(external)
);
// Write result file
await fs.writeFile(tmpFilePath, css);
return {
path: tmpFilePath,
watchFiles: sassRenderResult.loadedUrls
.filter((x) => x.protocol === "file:")
.map(url.fileURLToPath),
};
}
);
},
});
async function replaceUrls(
css: string,
newCssFileName: string,
sourceDir: string,
rootDir: string,
externals: WildcardPattern[]
): Promise<string> {
const ast = csstree.parse(css);
csstree.walk(ast, {
enter(node: CssNode) {
// Special case for import, since it supports raw strings as url
if (
node.type === "Atrule" &&
node.name === "import" &&
node.prelude != null &&
node.prelude.type === "AtrulePrelude"
) {
if (!node.prelude.children.isEmpty()) {
const urlNode = node.prelude.children.first();
if (urlNode != null && urlNode.type === "String") {
const normalizedUrl = normalizeQuotes(urlNode.value);
if (isLocalFileUrl(normalizedUrl)) {
const resolved = resolveUrl(normalizedUrl, sourceDir, rootDir);
const relativePath = path.relative(newCssFileName, resolved.file);
urlNode.value = `"${fixCssUrl(relativePath)}"`;
}
}
}
}
if (node.type === "Url") {
const value = node.value;
const normalizedUrl =
value.type === "String" ? normalizeQuotes(value.value) : value.value;
if (isExternal(normalizedUrl, externals)) {
return;
}
if (isLocalFileUrl(normalizedUrl)) {
const resolved = resolveUrl(normalizedUrl, sourceDir, rootDir);
const relativePath = path.relative(newCssFileName, resolved.file);
node.value = {
...node.value,
type: "String",
// disable keeping query and hash parts of original url, since esbuild doesn't support it yet
// value: `"${relativePath}${resolved.query}${resolved.hash}"`,
value: `"${fixCssUrl(relativePath)}"`,
};
}
}
},
});
return csstree.generate(ast);
}
function isLocalFileUrl(url: string): boolean {
if (/^https?:\/\//i.test(url)) {
return false;
}
if (/^data:/.test(url)) {
return false;
}
if (/^#/.test(url)) {
return false;
}
return true;
}
function normalizeQuotes(stringValue: string): string {
const match = stringValue.match(/^['"](.*)["']$/s);
return match != null ? match[1] ?? "" : stringValue;
}
// Always use unix-style path separator (/) in urls in CSS, since Windows-style
// separator doesn't work on Windows
function fixCssUrl(filePath: string): string {
return filePath.split(path.sep).join("/");
}
function resolveUrl(
url: string,
originalFolder: string,
rootDir: string
): {
file: string;
pathname: string;
query: string;
hash: string;
} {
const match = url.match(/^(.*?)(\?.*?)?(#.*?)?$/);
if (match == null) {
throw new Error(`Unable to parse url: ${url}`);
}
const [_, pathname = "", query, hash] = match;
let file = "";
if (pathname.startsWith("/")) {
file = path.resolve(rootDir, pathname.substring(1));
// todo: resolve by root dir
} else {
file = path.resolve(originalFolder, pathname);
}
return {
file,
pathname,
query: query || "",
hash: hash || "",
};
}