-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
48 lines (38 loc) · 1.18 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
46
47
48
const through = require('through2');
const { SourceNode, SourceMapConsumer } = require('source-map');
const { Buffer } = require('buffer');
// Helper
function prependStream(prependText) {
const stream = through();
stream.write(prependText);
return stream;
}
module.exports = function (str) {
async function prependText(file, encoding, callback) {
// Ignore empty file
if (file.isNull()) {
return callback(null, file);
}
// *** Update the source maps ***
if (file.sourceMap) {
const consumer = await new SourceMapConsumer(file.sourceMap);
const sourceNode = SourceNode.fromStringWithSourceMap(file.contents.toString(), consumer);
// Prepend the string
sourceNode.prepend(str);
// Update the source map of the file
const generator = sourceNode.toStringWithSourceMap({ file: file.sourceMap.file });
file.sourceMap = generator.map.toJSON();
}
// *** Update the file content ***
// Handle buffers
if (file.isBuffer()) {
file.contents = Buffer.from(`${str}${file.contents}`);
}
// Handle streams
if (file.isStream()) {
file.contents = file.contents.pipe(prependStream(str));
}
return callback(null, file);
}
return through.obj(prependText);
};