-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
82 lines (62 loc) · 1.92 KB
/
index.js
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
'use strict';
const postcss = require('postcss');
const path = require('path');
const map = require('multi-stage-sourcemap');
function processPlugin(plugin) {
// If plugin is a string, require the package that we assume it points to
if (typeof plugin === 'string') {
return require(plugin)();
}
return plugin;
}
module.exports = function(plugins, warnFn) {
plugins = plugins || [];
// Either process each if its an array, or directly if singular
if (typeof plugins.map !== 'undefined') {
plugins = plugins.map(processPlugin);
} else {
plugins = processPlugin(plugins);
}
// Return stylus function after postcss processing
return function(style) {
style = this || style;
let filename = style.options.filename;
// Grab stylus' ouput css before it's compiled to file
style.on('end', function(err, css) {
let processOptions,
processed,
comboMap;
// Exit on error
if (err){
return err;
}
processOptions = {
from: filename,
to: path.join(
path.dirname(filename),
path.basename(filename, path.extname(filename))
) + '.css'
};
// If stylus has a sourcemap, ensure postcss also generates one
if (style.sourcemap) {
processOptions.map = { annotation: false };
}
// Run postcss with user plugins
processed = postcss(plugins).process(css, processOptions);
// If sourcemaps generated, combine them
if (processed.map && style.sourcemap) {
comboMap = map.transfer({
fromSourceMap: processed.map.toString(),
toSourceMap: style.sourcemap
});
style.sourcemap = JSON.parse(comboMap);
}
// Pipe postcss errors to console
if (!warnFn || typeof warnFn !== 'function'){
warnFn = console.error;
}
processed.warnings().forEach(warnFn);
return processed.css;
});
};
};