This repository was archived by the owner on Jan 7, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
65 lines (52 loc) · 1.41 KB
/
index.js
File metadata and controls
65 lines (52 loc) · 1.41 KB
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
// through2 是一个对 node 的 transform streams 简单封装
var through = require('through2');
// var gutil = require('gulp-util');
// var PluginError = gutil.PluginError;
var fs = require('fs');
// 常量
const PLUGIN_NAME = 'gulp-code-replace';
// 公共变量
var errArr = [];
/**
* 文件内容处理
*
* @param {String} tmpPath 模版路径
* @param {String} str 文件内容
* @returns
*/
function codeRep(tmpPath, str) {
str = str.replace(/\{\{\s*([^}]+)\s*\}\}/g, function ($0, $1) {
var res = $0;
try {
res = fs.readFileSync(`${tmpPath}/${$1}`);
} catch (error) {
errArr.push(error);
// throw new PluginError(PLUGIN_NAME, `no such file or directory, open ${error.path}`);
} finally {
return res;
}
});
return str;
}
/**
* 插件入口
*
* @param {String} tmpPath
* @returns
*/
function gulpCodeReplace(tmpPath) {
return through.obj(function (file, enc, cb) {
if (file.isNull()) cb(null, file);
var result = codeRep(tmpPath, file.contents.toString());
if (file.isBuffer()) {
file.contents = new Buffer(result);
}
if (file.isStream()) {
var stream = through();
result = stream.write(result);
file.contents = file.contents.pipe(result);
}
cb(null, file);
});
};
module.exports = gulpCodeReplace;