-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (67 loc) · 2.35 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
66
67
68
69
70
71
72
73
74
75
76
77
var gutil = require('gulp-util');
var through = require('through2');
var iconv = require('iconv-lite');
var jschardet = require('jschardet');
var path = require('path');
module.exports = function(opt){
var options = {},opt = opt||{};
// 文件编码
// options.encode = opt.encode||"gbk";
// default:普通js字符串
// amd/cmd: 通用模块
options.type = opt.type||"default";
// modBase: 模块id基础路径
options.modBase = opt.modBase||"tpl";
function getFileName(filepath){
var fileBaseArr = filepath.split('.');
fileBaseArr.splice(-1);
return fileBaseArr.join('.');
}
function html2js(value) {
return value.replace(/^\s+|\s+$/g, '').replace(/(\r\n|\n)/g, "\\\n").replace(/'/g, "\\'");
}
function trans(file){
var output = {},
varName = '',
fileName = '';
encode = jschardet.detect(file.contents).encoding,
fileBasePath = path.basename(file.path),
filecontentTemp = iconv.decode(file.contents, encode);
// 文件名
fileName = filecontentTemp.match(/<!--filename:(\w+)-->/);
try{
output.fileName = fileName[1];
}catch(e){
output.fileName = getFileName(fileBasePath);
}
//js变量名
varName = filecontentTemp.match(/<!--varname:(\w+)-->/);
try{
output.varname = varName[1];
}catch(e){
output.varname = output.fileName;
}
filecontentTemp = html2js(filecontentTemp);
if(options.type=='amd' || options.type=='cmd' || options.type=='fmd'){
var amdId = options.modBase?options.modBase+'/'+output.fileName:output.fileName;
output.fileContent = 'define(function () {\n return \''+filecontentTemp+'\'\n});';
}else{
output.fileContent = output.varname+'=\'' + filecontentTemp + '\';';
}
return output;
}
return through.obj(function(file,enc,cb){
if (file.isNull()) {
return cb(null, file);
}
if (file.isStream()) {
return cb(new gutil.PluginError('gulp-tpl2js', 'Stream not supported'));
}
var compiledFile = trans(file);
var filename = gutil.replaceExtension(path.basename(file.path), '.js');
file.contents = iconv.encode(compiledFile.fileContent, encode);
file.path = path.join(file.base,gutil.replaceExtension(path.basename(file.path), '.js'));
this.push(file);
return cb();
});
}