UNPKG

1.55 kBJavaScriptView Raw
1'use strict';
2
3var through = require('through2');
4var stylus = require('accord').load('stylus');
5var gutil = require('gulp-util');
6var rext = require('replace-ext');
7var path = require('path');
8var _ = require('lodash');
9var applySourceMap = require('vinyl-sourcemaps-apply');
10
11var PLUGIN_NAME = 'gulp-stylus';
12
13module.exports = function (options) {
14 var opts = _.assign({}, options);
15
16 return through.obj(function (file, enc, cb) {
17
18 if (file.isStream()) {
19 return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
20 }
21 if (file.isNull()) {
22 return cb(null, file);
23 }
24 if (path.extname(file.path) === '.css') {
25 return cb(null, file);
26 }
27 if (file.sourceMap) {
28 opts.sourcemap = true;
29 }
30 opts.filename = file.path;
31
32 stylus.render(file.contents.toString('utf8'), opts)
33 .then(function(res) {
34 if (res.result !== undefined) {
35 file.path = rext(file.path, '.css');
36 file.contents = new Buffer(res.result);
37 if (res.sourcemap) {
38 makePathsRelative(file, res.sourcemap);
39 applySourceMap(file, res.sourcemap);
40 }
41 return cb(null, file);
42 }
43 })
44 .catch(function(err) {
45 return cb(new gutil.PluginError(PLUGIN_NAME, err));
46 });
47 });
48
49};
50
51function makePathsRelative(file, sourcemap) {
52 for (var i = 0; i < sourcemap.sources.length; i++) {
53 sourcemap.sources[i] = path.relative(file.base, sourcemap.sources[i]);
54 }
55}