-
Notifications
You must be signed in to change notification settings - Fork 295
/
stylesheet-processor.ts
135 lines (111 loc) · 4.29 KB
/
stylesheet-processor.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
import * as path from 'path';
import * as log from '../utils/log';
import { execSync } from 'child_process';
// CSS Tools
import * as autoprefixer from 'autoprefixer';
import * as browserslist from 'browserslist';
import * as nodeSassTildeImporter from 'node-sass-tilde-importer';
import * as postcss from 'postcss';
import * as postcssUrl from 'postcss-url';
import * as cssnanoPresetDefault from 'cssnano-preset-default';
import * as stylus from 'stylus';
export enum CssUrl {
inline = 'inline',
none = 'none',
}
/*
* Please be aware of the few differences in behaviour https://github.com/sass/dart-sass/blob/master/README.md#behavioral-differences-from-ruby-sass
* By default `npm install` will install sass.
* To use node-sass you need to use:
* Npm:
* `npm install node-sass --save-dev`
* Yarn:
* `yarn add node-sass --dev`
*/
let sassComplier: any | undefined;
try {
sassComplier = require('node-sass'); // Check if node-sass is explicitly included.
} catch {
sassComplier = require('sass');
}
export class StylesheetProcessor {
private postCssProcessor: postcss.Processor;
constructor(readonly basePath: string, readonly cssUrl?: CssUrl, readonly styleIncludePaths?: string[]) {
this.postCssProcessor = this.createPostCssProcessor(basePath, cssUrl);
}
process(filePath: string, content: string) {
// Render pre-processor language (sass, styl, less)
const renderedCss: string = this.renderPreProcessor(filePath, content);
// Render postcss (autoprefixing and friends)
const result = this.postCssProcessor.process(renderedCss, {
from: filePath,
to: filePath.replace(path.extname(filePath), '.css'),
});
// Log warnings from postcss
result.warnings().forEach((msg) => log.warn(msg.toString()));
return result.css;
}
private renderPreProcessor(filePath: string, content: string): string {
const ext = path.extname(filePath);
log.debug(`rendering ${ext} from ${filePath}`);
switch (ext) {
case '.sass':
case '.scss':
return sassComplier
.renderSync({
file: filePath,
data: content,
indentedSyntax: '.sass' === ext,
importer: nodeSassTildeImporter,
includePaths: this.styleIncludePaths,
})
.css.toString();
case '.less':
// this is the only way I found to make LESS sync
let cmd = `node "${require.resolve('less/bin/lessc')}" "${filePath}" --js`;
if (this.styleIncludePaths.length) {
cmd += ` --include-path="${this.styleIncludePaths.join(':')}"`;
}
return execSync(cmd).toString();
case '.styl':
case '.stylus':
return (
stylus(content)
// add paths for resolve
.set('paths', [this.basePath, '.', ...this.styleIncludePaths, 'node_modules'])
// add support for resolving plugins from node_modules
.set('filename', filePath)
// turn on url resolver in stylus, same as flag --resolve-url
.set('resolve url', true)
.define('url', stylus.resolver(undefined))
.render()
);
case '.css':
default:
return content;
}
}
private createPostCssProcessor(basePath: string, cssUrl?: CssUrl): postcss.Processor {
log.debug(`determine browserslist for ${basePath}`);
const overrideBrowserslist = browserslist(undefined, { path: basePath });
const postCssPlugins = [];
if (cssUrl !== CssUrl.none) {
log.debug(`postcssUrl: ${cssUrl}`);
postCssPlugins.push(postcssUrl({ url: cssUrl }));
}
// this is important to be executed post running `postcssUrl`
postCssPlugins.push(autoprefixer({ overrideBrowserslist, grid: true }));
const preset = cssnanoPresetDefault({
svgo: false,
// Disable calc optimizations due to several issues.
calc: false,
});
const asyncPlugins = ['postcss-svgo'];
const cssNanoPlugins = preset.plugins
// replicate the `initializePlugin` behavior from https://github.com/cssnano/cssnano/blob/a566cc5/packages/cssnano/src/index.js#L8
.map(([creator, pluginConfig]) => creator(pluginConfig))
.filter((plugin) => !asyncPlugins.includes(plugin.postcssPlugin));
postCssPlugins.push(...cssNanoPlugins);
return postcss(postCssPlugins);
}
}