forked from rvinokurov/advanced-preprocess-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (65 loc) · 2.32 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"use strict";
var path = require("path");
var process = require("process");
var crypto = require("crypto");
var pp = require("preprocess");
var loaderUtils = require("loader-utils");
var lodash_1 = require("lodash");
var mkdirp = require("mkdirp");
var fs = require("fs");
var algorithm = 'sha1', encoding = 'utf8', outputEncoding = 'hex', checksum = function (inputString) {
return crypto
.createHash(algorithm)
.update(inputString, encoding)
.digest(outputEncoding);
}, md5 = function (inputString) {
return crypto
.createHash('md5')
.update(inputString, encoding)
.digest(outputEncoding);
};
var createCacheFile = function (directory, resourcePath) {
mkdirp(directory, function (error) {
if (error) {
console.error(error);
}
else {
fs.writeFile(path.join(directory, md5(resourcePath)), '', { encoding: encoding }, function (error) {
if (error) {
console.error(error);
}
else {
// console.log('write', resourcePath);
}
});
}
});
};
var loader = function (content) {
this.cacheable && this.cacheable();
var resourcePath = this.resourcePath;
if (typeof resourcePath !== 'string' || !resourcePath.length) {
this.callback(null, content);
return;
}
content = lodash_1.trim(content);
var extension = path.extname(this.resourcePath).substring(1), sourceChecksum = checksum(content);
var options = {
srcDir: this.context,
type: extension
}, query = loaderUtils.getOptions(this) || {};
var preprocessCache = query.preprocessCache;
if (lodash_1.isObject(query.ppOptions)) {
options = lodash_1.merge(options, query.ppOptions);
}
var context = lodash_1.merge({}, process.env, query.context || {});
context.NODE_ENV = context.NODE_ENV || 'development';
var processed = lodash_1.trim(pp.preprocess(content, context, options));
var processedChecksum = checksum(processed);
if (sourceChecksum !== processedChecksum && typeof preprocessCache === 'string' && preprocessCache.length) {
// console.log(resourcePath);
createCacheFile(preprocessCache, resourcePath);
}
this.callback(null, processed);
};
module.exports = loader;