forked from daycool/gulp-iconfont-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
120 lines (97 loc) · 2.37 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
'use strict';
var path = require('path'),
gutil = require('gulp-util'),
consolidate = require('consolidate'),
_ = require('lodash'),
Stream = require('stream');
var PLUGIN_NAME = 'gulp-iconfont-template';
function iconfontTemplate(config) {
var glyphMap = [],
currentGlyph,
currentCodePoint,
inputFilePrefix,
stream,
outputFile,
engine,
cssClass;
// Set default values
config = _.merge({
path: 'html',
targetPath: 'template.html',
fontPath: './',
engine: 'lodash',
firstGlyph: 0xE001,
cssClass: 'icon'
}, config);
// Enable default html generators
if(!config.path) {
config.path = 'html';
}
if(/^(html)$/i.test(config.path)) {
config.path = __dirname + '/templates/template.' + config.path;
}
try {
engine = require(config.engine);
} catch(e) {
throw new gutil.PluginError(PLUGIN_NAME, 'Template engine "' + config.engine + '" not present');
}
// Define starting point
currentGlyph = config.firstGlyph;
// Happy streaming
stream = Stream.PassThrough({
objectMode: true
});
stream._transform = function(file, unused, cb) {
var fileName;
if (file.isNull()) {
this.push(file);
return cb();
}
// Create output file
if (!outputFile) {
outputFile = new gutil.File({
base: file.base,
cwd: file.cwd,
path: path.join(file.base, config.targetPath),
contents: file.isBuffer() ? new Buffer(0) : new Stream.PassThrough()
});
}
currentCodePoint = (currentGlyph++).toString(16).toUpperCase();
fileName = path.basename(file.path, '.svg');
glyphMap.push({
fileName: fileName,
codePoint: currentCodePoint
});
file.path = path.dirname(file.path) + '/' + path.basename(file.path);
this.push(file);
cb();
};
stream._flush = function(cb) {
var content;
if (glyphMap.length) {
consolidate[config.engine](config.path, {
glyphs: glyphMap,
fontName: config.fontName,
fontPath: config.fontPath,
cssClass: config.cssClass
}, function(err, html) {
if (err) {
throw new gutil.PluginError(PLUGIN_NAME, 'Error in template: ' + err.message);
}
content = Buffer(html);
if (outputFile.isBuffer()) {
outputFile.contents = content;
} else {
outputFile.contents.write(content);
outputFile.contents.end();
}
stream.push(outputFile);
cb();
});
} else {
cb();
}
};
return stream;
};
module.exports = iconfontTemplate;