UNPKG

1.31 kBJavaScriptView Raw
1'use strict';
2const through = require('through2');
3const _ = require('lodash');
4const rework = require('rework');
5const PluginError = require('plugin-error');
6const applySourceMap = require('vinyl-sourcemaps-apply');
7
8const lastIsObject = _.flowRight(_.isPlainObject, _.last);
9
10module.exports = (...args) => {
11 const options = Object.assign({}, lastIsObject(args) ? args.pop() : {});
12 const plugins = args;
13
14 return through.obj((file, enc, cb) => {
15 if (file.isNull()) {
16 cb(null, file);
17 return;
18 }
19
20 if (file.isStream()) {
21 cb(new PluginError('gulp-rework', 'Streaming not supported'));
22 return;
23 }
24
25 try {
26 const ret = rework(file.contents.toString(), {source: file.path});
27 plugins.forEach(ret.use.bind(ret));
28
29 if (file.sourceMap) {
30 options.sourcemap = true;
31 options.inputSourcemap = false;
32 options.sourcemapAsObject = true;
33 }
34
35 const result = ret.toString(options);
36 if (file.sourceMap) {
37 file.contents = Buffer.from(result.code);
38 result.map.file = file.relative;
39 result.map.sources = result.map.sources.map(() => file.relative);
40 applySourceMap(file, result.map);
41 } else {
42 file.contents = Buffer.from(result);
43 }
44
45 cb(null, file);
46 } catch (err) {
47 cb(new PluginError('gulp-rework', err, {fileName: err.filename || file.path}));
48 }
49 });
50};