1 | 'use strict';
|
2 |
|
3 | var through = require('through2');
|
4 | var stylus = require('accord').load('stylus');
|
5 | var gutil = require('gulp-util');
|
6 | var rext = require('replace-ext');
|
7 | var path = require('path');
|
8 | var _ = require('lodash');
|
9 | var applySourceMap = require('vinyl-sourcemaps-apply');
|
10 |
|
11 | var PLUGIN_NAME = 'gulp-stylus';
|
12 |
|
13 | module.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 | file.sourceMap.file = file.relative;
|
41 | }
|
42 | return cb(null, file);
|
43 | }
|
44 | })
|
45 | .catch(function(err) {
|
46 | return cb(new gutil.PluginError(PLUGIN_NAME, err));
|
47 | });
|
48 | });
|
49 |
|
50 | };
|
51 |
|
52 | function makePathsRelative(file, sourcemap) {
|
53 | for (var i = 0; i < sourcemap.sources.length; i++) {
|
54 | sourcemap.sources[i] = path.relative(file.base, sourcemap.sources[i]);
|
55 | }
|
56 | }
|