-
Notifications
You must be signed in to change notification settings - Fork 20
/
subsequent-plugins.js
79 lines (72 loc) · 1.9 KB
/
subsequent-plugins.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
const fs = require('fs');
const path = require('path');
const postcss = require('postcss');
const rootPath = require('app-root-path').path;
class SubsequentPlugins {
constructor() {
this.config = {};
this.updateConfig();
}
/**
* (Re)init with current postcss config
*/
_init() {
this.allNames = this.config.plugins ? Object.keys(this.config.plugins) : [];
this.subsequentNames = this.allNames.slice(
this.allNames.indexOf('postcss-extract-media-query') + 1
);
this.subsequentPlugins = this.subsequentNames.map((name) => ({
name,
mod:
(this.config.pluginsSrc && this.config.pluginsSrc[name]) ||
require(name),
opts: this.config.plugins[name],
}));
}
/**
* Updates the postcss config by resolving file path
* or by using the config file object
*
* @param {string|Object} file
* @returns {Object}
*/
updateConfig(file) {
if (typeof file === 'object') {
this.config = file;
this._init();
return this.config;
}
if (typeof file === 'string' && !path.isAbsolute(file)) {
file = path.join(rootPath, file);
}
const filePath = file || path.join(rootPath, 'postcss.config.js');
if (fs.existsSync(filePath)) {
this.config = require(filePath);
}
this._init();
return this.config;
}
/**
* Apply all subsequent plugins to the (extracted) css
*
* @param {string} css
* @param {string} filePath
* @returns {string}
*/
applyPlugins(css, filePath) {
const plugins = this.subsequentPlugins.map((plugin) =>
plugin.mod(plugin.opts)
);
if (plugins.length) {
return new Promise((resolve) => {
postcss(plugins)
.process(css, { from: filePath, to: filePath })
.then((result) => {
resolve(result.css);
});
});
}
return Promise.resolve(css);
}
}
module.exports = SubsequentPlugins;