-
Notifications
You must be signed in to change notification settings - Fork 74
/
getCssExports.ts
224 lines (198 loc) · 6.59 KB
/
getCssExports.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import path from 'path';
import Processor from 'postcss/lib/processor';
import less from 'less';
import sass from 'sass';
import stylus from 'stylus';
import { CSSExports, extractICSS } from 'icss-utils';
import { RawSourceMap } from 'source-map-js';
import type tsModule from 'typescript/lib/tsserverlibrary';
import { createMatchPath } from 'tsconfig-paths';
import { sassTildeImporter } from '../importers/sassTildeImporter';
import { Options, CustomRenderer } from '../options';
import { Logger } from './logger';
export const enum FileType {
css = 'css',
less = 'less',
sass = 'sass',
scss = 'scss',
styl = 'styl',
}
export const getFileType = (fileName: string): FileType => {
if (fileName.endsWith('.css')) return FileType.css;
if (fileName.endsWith('.less')) return FileType.less;
if (fileName.endsWith('.sass')) return FileType.sass;
if (fileName.endsWith('.styl')) return FileType.styl;
return FileType.scss;
};
const getFilePath = (fileName: string) => path.dirname(fileName);
export interface CSSExportsWithSourceMap {
classes: CSSExports;
css?: string;
sourceMap?: RawSourceMap;
}
export const getCssExports = ({
css,
fileName,
logger,
options,
processor,
compilerOptions,
directory,
}: {
css: string;
fileName: string;
logger: Logger;
options: Options;
processor: Processor;
compilerOptions: tsModule.CompilerOptions;
directory: string;
}): CSSExportsWithSourceMap => {
const rawCss = options.additionalData ? options.additionalData + css : css;
const fileType = getFileType(fileName);
const rendererOptions = options.rendererOptions ?? {};
let transformedCss = '';
let sourceMap: RawSourceMap | undefined;
try {
if (options.customRenderer) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const customRenderer = require(options.customRenderer) as CustomRenderer;
const result = customRenderer(rawCss, {
fileName,
logger,
compilerOptions,
});
if (typeof result === 'string') {
transformedCss = result;
} else if (result.css) {
transformedCss = result.css;
sourceMap = result.sourceMap;
}
} else {
switch (fileType) {
case FileType.less:
less.render(
rawCss,
{
syncImport: true,
filename: fileName,
paths: [directory],
sourceMap: true,
...(rendererOptions.less ?? {}),
} as Less.Options,
(error?: Less.RenderError, output?: Less.RenderOutput) => {
if (error) {
throw new Error(error.message);
}
if (output === undefined) {
throw new Error('No Less output.');
}
// This is typed as a `string`, but may be undefined.
const stringSourceMap = output.map as string | undefined;
sourceMap =
typeof stringSourceMap === 'string'
? (JSON.parse(stringSourceMap) as RawSourceMap)
: undefined;
transformedCss = output.css.toString();
},
);
break;
case FileType.scss:
case FileType.sass: {
const filePath = getFilePath(fileName);
const { loadPaths, ...sassOptions } = rendererOptions.sass ?? {};
const { baseUrl = directory, paths } = compilerOptions;
const matchPath =
baseUrl && paths
? createMatchPath(path.resolve(baseUrl), paths)
: null;
const aliasImporter: sass.FileImporter<'sync'> = {
findFileUrl(url) {
const exactFileUrl = matchPath?.(url, undefined, undefined, [
'.sass',
'.scss',
]);
if (exactFileUrl) {
return new URL(`file://${exactFileUrl}`);
}
/*
* In case it didn't find the exact file it'll proceed to
* check other files matching the import process of Sass
* guidelines:
* https://sass-lang.com/documentation/at-rules/import/#partials
* https://sass-lang.com/documentation/at-rules/import/#index-files
*/
// Checks for partials
const partialFileName = path.basename(url);
const partialDirName = path.dirname(url);
const partialFilePath = path.join(
partialDirName,
`_${partialFileName}`,
);
const partialFileUrl =
matchPath !== null
? matchPath(partialFilePath, undefined, undefined, [
'.sass',
'.scss',
])
: undefined;
if (partialFileUrl) {
return new URL(`file://${partialFileUrl}`);
}
// Checks for an _index file
const indexFilePath = path.join(
partialDirName,
partialFileName,
`_index`,
);
const indexFileUrl =
matchPath !== null
? matchPath(indexFilePath, undefined, undefined, [
'.sass',
'.scss',
])
: undefined;
return indexFileUrl ? new URL(`file://${indexFileUrl}`) : null;
},
};
const importers = [aliasImporter, sassTildeImporter];
const result = sass.compileString(rawCss, {
importers,
loadPaths: [filePath, 'node_modules', ...(loadPaths ?? [])],
sourceMap: true,
syntax: fileType === FileType.sass ? 'indented' : 'scss',
url: new URL(`file://${fileName}`),
...sassOptions,
});
sourceMap = result.sourceMap;
transformedCss = result.css.toString();
break;
}
case FileType.styl:
transformedCss = stylus(rawCss, {
...(rendererOptions.stylus ?? {}),
filename: fileName,
}).render();
break;
default:
transformedCss = rawCss;
break;
}
}
const processedCss = processor.process(transformedCss, {
from: fileName,
map: {
inline: false,
prev: sourceMap,
},
});
return {
classes: extractICSS(processedCss.root).icssExports,
css: processedCss.css,
sourceMap: processedCss.map.toJSON(),
};
} catch (e) {
console.error(e);
logger.error(e);
return { classes: {} };
}
};