-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (82 loc) · 2.11 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
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
const Transform = require('stream').Transform;
const PostCSS = require('postcss');
const Tool = function(fuller, options) {
fuller.bind(this);
const opts = options.postcss;
this.map = opts.map;
this.warnings = options.warnings || opts.warnings;
this.processor = PostCSS(this.loadPlugins(opts.plugins));
};
Tool.prototype = {
build: function() {
return new Transform({
objectMode: true,
transform: (mat, enc, next) => this.process(mat, err => next(err, mat))
});
},
process: function(mat, next) {
mat.getContent(content => this.processor
.process(content.toString(), {
from: mat.src.path,
to: mat.dst().path,
map: this.map
})
.then(result => {
this.processResult(result, mat.id);
mat.setContent(result.css);
if (result.map) {
mat.map = result.map;
}
next(null, mat);
})
.catch(error => {
this.processError(error);
next();
})
)
},
processResult: function(result, matId) {
if (result.messages) {
result.messages.forEach(message => {
if (message.type === 'dependency') {
this.addDependencies(message.file, matId);
}
});
}
if (this.warnings) {
result
.warnings()
.forEach(warn => this.log(warn.toString()));
}
},
processError: function(error) {
if (error.name === 'CssSyntaxError') {
this.error({
message: error.reason,
file: error.file,
line: error.line,
column: error.column,
extract: error.showSourceCode()
});
} else {
this.error(error);
}
},
loadPlugins: function(plugins) {
if (!plugins) {
throw Error('No postcss plugins are defined');
}
return plugins
.filter(plugin => plugin) // skip falsy values
.map(plugin => {
if (typeof plugin === 'string') {
return this.require(plugin);
}
const name = Object.keys(plugin)[0];
const module = this.require(name);
return module(plugin[name]);
})
}
};
module.exports = Tool;