-
Notifications
You must be signed in to change notification settings - Fork 3
/
svg2font-cli.js
282 lines (243 loc) · 9.3 KB
/
svg2font-cli.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/env node
var ArgumentParser = require('argparse').ArgumentParser;
var fs = require('fs');
var fontCarrier = require('font-carrier')
var path = require('path');
var pinyin = require("pinyin");
var DOMParser = require('xmldom').DOMParser
var svgPathify = require('svg_pathify');
var unicodeNum = 60000;
var fileName = 'iconfont';
var fontFamily = 'iconfont';
var fontClass = 'icon-';
var cssItems = [];
var symbols = [];
var demoUnicodeList = [];
var demoClassList = [];
var demoSymbolList = [];
var parser = new ArgumentParser({
version: require('./package.json').version,
addHelp: true,
description: '通过svg图标生成目前浏览器支持的多种字体文件'
});
parser.addArgument(
['inputPath'],
{
help: 'Input path',
type: 'string'
}
);
parser.addArgument(
['outputPath'],
{
help: 'Output path',
type: 'string'
}
);
parser.addArgument(
['-u', '--unicodeNum'],
{
help: 'unicodeNum, default 60000',
required: false,
type: 'int'
}
);
parser.addArgument(
['-n', '--fileName'],
{
help: 'fileName, default iconfont',
required: false,
type: 'string'
}
);
parser.addArgument(
['-f', '--fontFamily'],
{
help: 'fontFamily, default iconfont',
required: false,
type: 'string'
}
);
parser.addArgument(
['-c', '--fontClass'],
{
help: 'fontClass, default icon-',
required: false,
type: 'string'
}
);
parser.addArgument(
['-r', '--reverse'],
{
help: 'font to svg',
required: false,
type: 'string'
}
);
var args = parser.parseArgs();
var mkdirSync = function (dirname, callback) {
const exists = fs.existsSync(dirname);
if (exists) {
callback();
} else {
mkdirSync(path.dirname(dirname), function () {
fs.mkdir(dirname, callback);
});
}
};
if (args.reverse) {
try {
mkdirSync(outputPath, () => {
var glyphs = fontCarrier.transfer(args.inputPath).allGlyph();
const svgs = [];
for (key in glyphs) {
if (key == "x") {
continue;
}
var svg = glyphs[key].toSvg();
var glyphName = glyphs[key].options.name || glyphs[key].options.glyphName || key.slice(1);
svgs.push([
`<li class="dib">`,
` <img class="icon svg-icon" src="data:image/svg+xml;base64,${new Buffer(svg).toString('base64')}" alt=""></img>`,
` <div class="name">${glyphName}</div>`,
` <div class="code-name">${key.slice(1)}</div>`,
`</li>`
].join('\n'));
fs.writeFileSync(path.join(args.outputPath, glyphName + '.svg'), svg);
}
let template = fs.readFileSync(path.join(__dirname, 'template', 'demo_svg.html')).toString();
template = template.replace('<div id="svg-list"></div>', svgs.join('\n\n'));
fs.writeFileSync(path.join(args.outputPath, 'demo_svg.html'), template);
});
} catch (e) {
console.error(e);
console.error("Can't open input file (%s)", args.inputPath);
process.exit(1);
}
return;
}
if (args.unicodeNum) unicodeNum = args.unicodeNum;
if (args.fileName) fileName = args.fileName;
if (args.fontFamily) fontFamily = args.fontFamily;
if (args.fontClass) fontClass = args.fontClass;
try {
var travel = function (dir) {
if (!fs.statSync(dir).isDirectory()) {
if (path.extname(dir) === '.svg') {
readSvg(dir);
}
} else {
fs.readdirSync(dir).forEach(function (file) {
var pathname = path.join(dir, file);
if (fs.statSync(pathname).isDirectory()) {
travel(pathname);
} else {
if (path.extname(pathname) === '.svg') {
readSvg(pathname);
}
}
});
}
}
var readSvg = function (dir) {
const unicode = '&#' + ++unicodeNum + ';';
const glyph = fs.readFileSync(dir).toString();
const svgDocNode = (new DOMParser()).parseFromString(svgPathify(glyph), 'application/xml');
const pathNode = svgDocNode.getElementsByTagName('path').toString();
const glyphName = path.basename(dir).split('.')[0];
const pinyinStr = pinyin(glyphName, { style: pinyin.STYLE_NORMAL }).join("");
const className = fontClass + pinyinStr;
const content = '\\' + unicodeNum.toString(16);
demoUnicodeList.push([
`<li class="dib">`,
` <span class="icon ${fontFamily}">&#x${unicodeNum.toString(16)};</span>`,
` <div class="name">${glyphName}</div>`,
` <div class="code-name">&#x${unicodeNum.toString(16)};</div>`,
`</li>`
].join('\n'));
demoClassList.push([
`<li class="dib">`,
` <span class="icon ${fontFamily} ${className}"></span>`,
` <div class="name">${glyphName}</div>`,
` <div class="code-name">.${className}</div>`,
`</li>`
].join('\n'));
demoSymbolList.push([
`<li class="dib">`,
` <svg class="icon svg-icon" aria-hidden="true">`,
` <use xlink:href="#${className}"></use>`,
` </svg>`,
` <div class="name">${glyphName}</div>`,
` <div class="code-name">#${className}</div>`,
`</li>`
].join('\n'));
symbols.push(`<symbol id="${className}" viewBox="0 0 1024 1024">${pathNode}</symbol>`);
const items = [
`.${className}:before {`,
` content: "${content}";`,
`}`
];
cssItems.push(items.join('\n'));
font.setGlyph(unicode, {
svg: glyph,
glyphName: pinyinStr
});
}
var outputCssJs = function () {
//输出css文件
const woff2 = fs.readFileSync(path.join(args.outputPath, fileName) + '.woff2').toString()
const base64 = Buffer.from(woff2).toString('base64')
const timestamp = new Date().getTime();
const cssStr = [
`@font-face {`,
` font-family: "${fontFamily}";`,
` src: url('${fileName}.eot?t=${timestamp}'); /* IE9 */`,
` src: url('${fileName}.eot?t=${timestamp}#iefix') format('embedded-opentype'), /* IE6-IE8 */`,
` url('data:application/x-font-woff2;charset=utf-8;base64,${base64}') format('woff2'),`,
` url('${fileName}.woff?t=${timestamp}') format('woff'),`,
` url('${fileName}.ttf?t=${timestamp}') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */`,
` url('${fileName}.svg?t=${timestamp}#${fontFamily}') format('svg'); /* iOS 4.1- */`,
`}\n`,
`.${fontFamily} {`,
` font-family: "${fontFamily}" !important;`,
` font-size: 16px;`,
` font-style: normal;`,
` -webkit-font-smoothing: antialiased;`,
` -moz-osx-font-smoothing: grayscale;`,
`}\n\n`
].join('\n') + cssItems.join('\n\n');
fs.writeFileSync(path.join(args.outputPath, fileName + '.css'), cssStr);
//输出js文件
const jsStr = `!function (a) { var t, c = '<svg>${symbols.join('')}</svg>', e = (t = document.getElementsByTagName("script"))[t.length - 1].getAttribute("data-injectcss"); if (e && !a.__iconfont__svg__cssinject__) { a.__iconfont__svg__cssinject__ = !0; try { document.write("<style>.svgfont {display: inline-block;width: 1em;height: 1em;fill: currentColor;vertical-align: -0.1em;font-size:16px;}</style>") } catch (t) { console && console.log(t) } } !function (t) { if (document.addEventListener) if (~["complete", "loaded", "interactive"].indexOf(document.readyState)) setTimeout(t, 0); else { var e = function () { document.removeEventListener("DOMContentLoaded", e, !1), t() }; document.addEventListener("DOMContentLoaded", e, !1) } else document.attachEvent && (n = t, l = a.document, o = !1, (i = function () { try { l.documentElement.doScroll("left") } catch (t) { return void setTimeout(i, 50) } c() })(), l.onreadystatechange = function () { "complete" == l.readyState && (l.onreadystatechange = null, c()) }); function c() { o || (o = !0, n()) } var n, l, o, i }(function () { var t, e; (t = document.createElement("div")).innerHTML = c, c = null, (e = t.getElementsByTagName("svg")[0]) && (e.setAttribute("aria-hidden", "true"), e.style.position = "absolute", e.style.width = 0, e.style.height = 0, e.style.overflow = "hidden", function (t, e) { e.firstChild ? function (t, e) { e.parentNode.insertBefore(t, e) }(t, e.firstChild) : e.appendChild(t) }(e, document.body)) }) }(window);`
fs.writeFileSync(path.join(args.outputPath, fileName + '.js'), jsStr);
};
var outputDemo = function () {
//输出demo-html
let demoHtmlStr = fs.readFileSync(path.join(__dirname, 'template', 'demo_index.html')).toString();
demoHtmlStr = demoHtmlStr.replace('<div id="unicode-list"></div>', demoUnicodeList.join('\n\n'));
demoHtmlStr = demoHtmlStr.replace('<div id="class-list"></div>', demoClassList.join('\n\n'));
demoHtmlStr = demoHtmlStr.replace('<div id="symbol-list"></div>', demoSymbolList.join('\n\n'));
demoHtmlStr = demoHtmlStr.replace('iconfont.css', `${fileName}.css`);
demoHtmlStr = demoHtmlStr.replace('iconfont.js', `${fileName}.js`);
fs.writeFileSync(path.join(args.outputPath, 'demo_index.html'), demoHtmlStr);
//输出demo-css
fs.copyFileSync(path.join(__dirname, 'template', 'demo.css'), path.join(args.outputPath, 'demo.css'));
};
const font = fontCarrier.create();
font.setFontface({
fontFamily: fontFamily
});
travel(args.inputPath);
mkdirSync(outputPath, () => {
//输出字体文件
font.output({
path: path.join(args.outputPath, fileName)
});
outputCssJs(outputPath);
outputDemo();
});
} catch (e) {
console.error(e);
console.error("Can't open input file (%s)", args.inputPath);
process.exit(1);
}