UNPKG

1.95 kBJavaScriptView Raw
1'use strict';
2
3var postcss = require('postcss'),
4 path = require('path'),
5 map = require('multi-stage-sourcemap');
6
7module.exports = function (plugins, warnFn) {
8
9 plugins = plugins || [];
10
11 var processPlugin = function(plugin) {
12
13 // If plugin is a string, require the package that we assume it points to
14 if (typeof plugin === 'string') {
15 return require(plugin)();
16 }
17
18 return plugin;
19 };
20
21 // Either process each if its an array, or directly if singular
22 if (typeof plugins.map !== 'undefined') {
23 plugins = plugins.map(processPlugin);
24 } else {
25 plugins = processPlugin(plugins);
26 }
27
28 // Return stylus function after postcss processing
29 return function(style) {
30 style = this || style;
31 var filename = style.options.filename;
32
33 // Grab stylus' ouput css before it's compiled to file
34 style.on('end', function(err, css) {
35
36 // Exit on error
37 if (err){
38 return err;
39 }
40
41 // Postcss options
42 var processOptions = {
43 from: filename,
44 to: path.join(
45 path.dirname(filename),
46 path.basename(filename, path.extname(filename))
47 ) + '.css'
48 };
49
50 // If stylus has a sourcemap, ensure postcss also generates one
51 if (style.sourcemap) {
52 processOptions.map = { annotation: false };
53 }
54
55 // Run postcss with user plugins
56 var processed = postcss(plugins).process(css, processOptions);
57
58 // If sourcemaps generated, combine them
59 if (processed.map && style.sourcemap) {
60
61 var comboMap = map.transfer({
62 fromSourceMap: processed.map.toString(),
63 toSourceMap: style.sourcemap
64 });
65
66 style.sourcemap = JSON.parse(comboMap);
67
68 }
69
70 // Pipe postcss errors to console
71 if (!warnFn || typeof warnFn !== 'function'){
72 warnFn = console.error;
73 }
74
75 processed.warnings().forEach(warnFn);
76
77 return processed.css;
78
79 });
80
81 };
82};