This repository was archived by the owner on May 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 309
/
Copy pathsass.ts
executable file
·481 lines (379 loc) · 15.2 KB
/
sass.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import { basename, dirname, join, sep } from 'path';
import { BuildContext, BuildState, ChangedFile, TaskInfo } from './util/interfaces';
import { BuildError } from './util/errors';
import { bundle } from './bundle';
import { ensureDirSync, readdirSync, writeFile } from 'fs-extra';
import { fillConfigDefaults, getUserConfigFile, replacePathVars } from './util/config';
import { Logger } from './logger/logger';
import { runSassDiagnostics } from './logger/logger-sass';
import { printDiagnostics, clearDiagnostics, DiagnosticsType } from './logger/logger-diagnostics';
import { SassError, render as nodeSassRender, Result } from 'node-sass';
import * as postcss from 'postcss';
import * as autoprefixer from 'autoprefixer';
export function sass(context: BuildContext, configFile?: string) {
configFile = getUserConfigFile(context, taskInfo, configFile);
const logger = new Logger('sass');
return sassWorker(context, configFile)
.then(outFile => {
context.sassState = BuildState.SuccessfulBuild;
logger.finish();
return outFile;
})
.catch(err => {
context.sassState = BuildState.RequiresBuild;
throw logger.fail(err);
});
}
export function sassUpdate(changedFiles: ChangedFile[], context: BuildContext) {
const configFile = getUserConfigFile(context, taskInfo, null);
const logger = new Logger('sass update');
return sassWorker(context, configFile)
.then(outFile => {
context.sassState = BuildState.SuccessfulBuild;
logger.finish();
return outFile;
})
.catch(err => {
context.sassState = BuildState.RequiresBuild;
throw logger.fail(err);
});
}
export function sassWorker(context: BuildContext, configFile: string) {
const sassConfig: SassConfig = getSassConfig(context, configFile);
const bundlePromise: Promise<any>[] = [];
if (!context.moduleFiles && !sassConfig.file) {
// sass must always have a list of all the used module files
// so ensure we bundle if moduleFiles are currently unknown
bundlePromise.push(bundle(context));
}
return Promise.all(bundlePromise).then(() => {
clearDiagnostics(context, DiagnosticsType.Sass);
// where the final css output file is saved
if (!sassConfig.outFile) {
sassConfig.outFile = join(context.buildDir, sassConfig.outputFilename);
}
Logger.debug(`sass outFile: ${sassConfig.outFile}`);
// import paths where the sass compiler will look for imports
sassConfig.includePaths.unshift(join(context.srcDir));
Logger.debug(`sass includePaths: ${sassConfig.includePaths}`);
// sass import sorting algorithms incase there was something to tweak
sassConfig.sortComponentPathsFn = (sassConfig.sortComponentPathsFn || defaultSortComponentPathsFn);
sassConfig.sortComponentFilesFn = (sassConfig.sortComponentFilesFn || defaultSortComponentFilesFn);
if (!sassConfig.file) {
// if the sass config was not given an input file, then
// we're going to dynamically generate the sass data by
// scanning through all the components included in the bundle
// and generate the sass on the fly
generateSassData(context, sassConfig);
} else {
sassConfig.file = replacePathVars(context, sassConfig.file);
}
return render(context, sassConfig);
});
}
export function getSassConfig(context: BuildContext, configFile: string): SassConfig {
configFile = getUserConfigFile(context, taskInfo, configFile);
return fillConfigDefaults(configFile, taskInfo.defaultConfigFile);
}
function generateSassData(context: BuildContext, sassConfig: SassConfig) {
/**
* 1) Import user sass variables first since user variables
* should have precedence over default library variables.
* 2) Import all library sass files next since library css should
* be before user css, and potentially have library css easily
* overridden by user css selectors which come after the
* library's in the same file.
* 3) Import the user's css last since we want the user's css to
* potentially easily override library css with the same
* css specificity.
*/
const moduleDirectories: string[] = [];
if (context.moduleFiles) {
context.moduleFiles.forEach(moduleFile => {
const moduleDirectory = dirname(moduleFile);
if (moduleDirectories.indexOf(moduleDirectory) < 0) {
moduleDirectories.push(moduleDirectory);
}
});
}
Logger.debug(`sass moduleDirectories: ${moduleDirectories.length}`);
// gather a list of all the sass variable files that should be used
// these variable files will be the first imports
const userSassVariableFiles = sassConfig.variableSassFiles.map(f => {
return replacePathVars(context, f);
});
// gather a list of all the sass files that are next to components we're bundling
const componentSassFiles = getComponentSassFiles(moduleDirectories, context, sassConfig);
Logger.debug(`sass userSassVariableFiles: ${userSassVariableFiles.length}`);
Logger.debug(`sass componentSassFiles: ${componentSassFiles.length}`);
const sassImports = userSassVariableFiles.concat(componentSassFiles).map(sassFile => '"' + sassFile.replace(/\\/g, '\\\\') + '"');
if (sassImports.length) {
sassConfig.data = `@charset "UTF-8"; @import ${sassImports.join(',')};`;
}
}
function getComponentSassFiles(moduleDirectories: string[], context: BuildContext, sassConfig: SassConfig) {
const collectedSassFiles: string[] = [];
const componentDirectories = getComponentDirectories(moduleDirectories, sassConfig);
// sort all components with the library components being first
// and user components coming last, so it's easier for user css
// to override library css with the same specificity
const sortedComponentPaths = componentDirectories.sort(sassConfig.sortComponentPathsFn);
sortedComponentPaths.forEach(componentPath => {
addComponentSassFiles(componentPath, collectedSassFiles, context, sassConfig);
});
return collectedSassFiles;
}
function addComponentSassFiles(componentPath: string, collectedSassFiles: string[], context: BuildContext, sassConfig: SassConfig) {
let siblingFiles = getSiblingSassFiles(componentPath, sassConfig);
if (!siblingFiles.length && componentPath.indexOf(sep + 'node_modules') === -1) {
// if we didn't find anything, see if this module is mapped to another directory
for (const k in sassConfig.directoryMaps) {
if (sassConfig.directoryMaps.hasOwnProperty(k)) {
var actualDirectory = replacePathVars(context, k);
var mappedDirectory = replacePathVars(context, sassConfig.directoryMaps[k]);
componentPath = componentPath.replace(actualDirectory, mappedDirectory);
siblingFiles = getSiblingSassFiles(componentPath, sassConfig);
if (siblingFiles.length) {
break;
}
}
}
}
if (siblingFiles.length) {
siblingFiles = siblingFiles.sort(sassConfig.sortComponentFilesFn);
siblingFiles.forEach(componentFile => {
collectedSassFiles.push(componentFile);
});
}
}
function getSiblingSassFiles(componentPath: string, sassConfig: SassConfig) {
try {
return readdirSync(componentPath).filter(f => {
return isValidSassFile(f, sassConfig);
}).map(f => {
return join(componentPath, f);
});
} catch (ex) {
// it's an invalid path
return [];
}
}
function isValidSassFile(filename: string, sassConfig: SassConfig) {
for (var i = 0; i < sassConfig.includeFiles.length; i++) {
if (sassConfig.includeFiles[i].test(filename)) {
// filename passes the test to be included
for (var j = 0; j < sassConfig.excludeFiles.length; j++) {
if (sassConfig.excludeFiles[j].test(filename)) {
// however, it also passed the test that it should be excluded
Logger.debug(`sass excluded: ${filename}`);
return false;
}
}
return true;
}
}
return false;
}
function getComponentDirectories(moduleDirectories: string[], sassConfig: SassConfig) {
// filter out module directories we know wouldn't have sibling component sass file
// just a way to reduce the amount of lookups to be done later
return moduleDirectories.filter(moduleDirectory => {
// normalize this directory is using / between directories
moduleDirectory = moduleDirectory.replace(/\\/g, '/');
for (var i = 0; i < sassConfig.excludeModules.length; i++) {
if (moduleDirectory.indexOf('/node_modules/' + sassConfig.excludeModules[i] + '/') > -1) {
return false;
}
}
return true;
});
}
function render(context: BuildContext, sassConfig: SassConfig): Promise<string> {
return new Promise((resolve, reject) => {
sassConfig.omitSourceMapUrl = false;
if (sassConfig.sourceMap) {
sassConfig.sourceMapContents = true;
}
nodeSassRender(sassConfig, (sassError: SassError, sassResult: Result) => {
const diagnostics = runSassDiagnostics(context, sassError);
if (diagnostics.length) {
printDiagnostics(context, DiagnosticsType.Sass, diagnostics, true, true);
// sass render error :(
reject(new BuildError('Failed to render sass to css'));
} else {
// sass render success :)
renderSassSuccess(context, sassResult, sassConfig).then(outFile => {
resolve(outFile);
}).catch(err => {
reject(new BuildError(err));
});
}
});
});
}
function renderSassSuccess(context: BuildContext, sassResult: Result, sassConfig: SassConfig): Promise<string> {
if (sassConfig.autoprefixer) {
// with autoprefixer
let autoPrefixerMapOptions: any = false;
if (sassConfig.sourceMap) {
autoPrefixerMapOptions = {
inline: false,
prev: generateSourceMaps(sassResult, sassConfig)
};
}
const postcssOptions: any = {
to: basename(sassConfig.outFile),
map: autoPrefixerMapOptions,
from: void 0
};
Logger.debug(`sass, start postcss/autoprefixer`);
let postCssPlugins = [autoprefixer(sassConfig.autoprefixer)];
if (sassConfig.postCssPlugins) {
postCssPlugins = [
...sassConfig.postCssPlugins,
...postCssPlugins
];
}
return postcss(postCssPlugins)
.process(sassResult.css, postcssOptions).then((postCssResult: any) => {
postCssResult.warnings().forEach((warn: any) => {
Logger.warn(warn.toString());
});
let apMapResult: SassMap = null;
if (sassConfig.sourceMap && postCssResult.map) {
Logger.debug(`sass, parse postCssResult.map`);
apMapResult = generateSourceMaps(postCssResult, sassConfig);
}
Logger.debug(`sass: postcss/autoprefixer completed`);
return writeOutput(context, sassConfig, postCssResult.css, apMapResult);
});
}
// without autoprefixer
let sassMapResult: SassMap = generateSourceMaps(sassResult, sassConfig);
return writeOutput(context, sassConfig, sassResult.css.toString(), sassMapResult);
}
function generateSourceMaps(sassResult: Result, sassConfig: SassConfig): SassMap {
// this can be async and nothing needs to wait on it
// build Source Maps!
if (sassResult.map) {
Logger.debug(`sass, generateSourceMaps`);
// transform map into JSON
const sassMap: SassMap = JSON.parse(sassResult.map.toString());
// grab the stdout and transform it into stdin
const sassMapFile = sassMap.file.replace(/^stdout$/, 'stdin');
// grab the base file name that's being worked on
const sassFileSrc = sassConfig.outFile;
// grab the path portion of the file that's being worked on
const sassFileSrcPath = dirname(sassFileSrc);
if (sassFileSrcPath) {
// prepend the path to all files in the sources array except the file that's being worked on
const sourceFileIndex = sassMap.sources.indexOf(sassMapFile);
sassMap.sources = sassMap.sources.map((source, index) => {
return (index === sourceFileIndex) ? source : join(sassFileSrcPath, source);
});
}
// remove 'stdin' from souces and replace with filenames!
sassMap.sources = sassMap.sources.filter(src => {
if (src !== 'stdin') {
return src;
}
});
return sassMap;
}
}
function writeOutput(context: BuildContext, sassConfig: SassConfig, cssOutput: string, sourceMap: SassMap): Promise<string> {
let mappingsOutput: string = JSON.stringify(sourceMap);
return new Promise((resolve, reject) => {
Logger.debug(`sass start write output: ${sassConfig.outFile}`);
const buildDir = dirname(sassConfig.outFile);
ensureDirSync(buildDir);
writeFile(sassConfig.outFile, cssOutput, (cssWriteErr: any) => {
if (cssWriteErr) {
reject(new BuildError(`Error writing css file, ${sassConfig.outFile}: ${cssWriteErr}`));
} else {
Logger.debug(`sass saved output: ${sassConfig.outFile}`);
if (mappingsOutput) {
// save the css map file too
// this save completes async and does not hold up the resolve
const sourceMapPath = join(buildDir, basename(sassConfig.outFile) + '.map');
Logger.debug(`sass start write css map: ${sourceMapPath}`);
writeFile(sourceMapPath, mappingsOutput, (mapWriteErr: any) => {
if (mapWriteErr) {
Logger.error(`Error writing css map file, ${sourceMapPath}: ${mapWriteErr}`);
} else {
Logger.debug(`sass saved css map: ${sourceMapPath}`);
}
});
}
// css file all saved
// note that we're not waiting on the css map to finish saving
resolve(sassConfig.outFile);
}
});
});
}
function defaultSortComponentPathsFn(a: any, b: any): number {
const aIndexOfNodeModules = a.indexOf('node_modules');
const bIndexOfNodeModules = b.indexOf('node_modules');
if (aIndexOfNodeModules > -1 && bIndexOfNodeModules > -1) {
return (a > b) ? 1 : -1;
}
if (aIndexOfNodeModules > -1 && bIndexOfNodeModules === -1) {
return -1;
}
if (aIndexOfNodeModules === -1 && bIndexOfNodeModules > -1) {
return 1;
}
return (a > b) ? 1 : -1;
}
function defaultSortComponentFilesFn(a: any, b: any): number {
const aPeriods = a.split('.').length;
const bPeriods = b.split('.').length;
const aDashes = a.split('-').length;
const bDashes = b.split('-').length;
if (aPeriods > bPeriods) {
return 1;
} else if (aPeriods < bPeriods) {
return -1;
}
if (aDashes > bDashes) {
return 1;
} else if (aDashes < bDashes) {
return -1;
}
return (a > b) ? 1 : -1;
}
const taskInfo: TaskInfo = {
fullArg: '--sass',
shortArg: '-s',
envVar: 'IONIC_SASS',
packageConfig: 'ionic_sass',
defaultConfigFile: 'sass.config'
};
export interface SassConfig {
// https://www.npmjs.com/package/node-sass
outputFilename?: string;
outFile?: string;
file?: string;
data?: string;
includePaths?: string[];
excludeModules?: string[];
includeFiles?: RegExp[];
excludeFiles?: RegExp[];
directoryMaps?: { [key: string]: string };
sortComponentPathsFn?: (a: any, b: any) => number;
sortComponentFilesFn?: (a: any, b: any) => number;
variableSassFiles?: string[];
autoprefixer?: any;
sourceMap?: string;
omitSourceMapUrl?: boolean;
sourceMapContents?: boolean;
postCssPlugins?: any[];
}
export interface SassMap {
version: number;
file: string;
sources: string[];
mappings: string;
names: any[];
}