-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
45 lines (42 loc) · 2.01 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
/* eslint-disable import/no-extraneous-dependencies */
const fs = require('fs');
const postcss = require('postcss');
let moduleValuesPlugin = require('postcss-modules-values-replace');
moduleValuesPlugin = moduleValuesPlugin.default || moduleValuesPlugin;
/**
* Extracts all CSS Module @values from a list of css files into an object.
* @param {Object} options
* @param {Array} options.files - list of fully-qualified css file names to extract @values from, for example for all .css files current dir:
* const path = require('path');
* const cssFiles = fs.readdirSync(__dirname).filter((file) => file.match(/\.css/i)).map((file) => path.resolve(__dirname, file));
* @param {Array} [options.plugins] - list of postcss plugin functions to use in processing, i.e.:
* [require('postcss-calc'), require('precss')]
* @returns {Promise|Object} - returns a promise which resolves to an object with values from all files combined.
*/
function extractValues(options = {}) {
const variables = {};
const plugins = options.plugins || [];
const processor = postcss([moduleValuesPlugin].concat(plugins));
const files = options.files || [];
return new Promise((resolve, reject) => {
const promises = [];
files.forEach((file) => {
const css = fs.readFileSync(file);
// from/to below required by postcss for sourceMap, not actually used to read/write file:
promises.push(processor
.process(css, { from: file, to: `${file}.js` })
.then(result => {
if (result.messages.length) {
const foundValues = result.messages
.filter((message) => message.plugin === 'postcss-modules-values-replace' && message.type === 'values')
.map((message) => message.values);
Object.assign(variables, ...foundValues); // in theory we support multiple messages from the plugin
}
}));
});
Promise.all(promises).then(() => {
resolve(variables);
}).catch(reject);
});
}
module.exports = extractValues;