UNPKG

3.26 kBJavaScriptView Raw
1/*
2 生成字体文件,
3 生成字体 content
4 */
5'use strict';
6var fs = require('fs'),
7 path = require('path'),
8 fontCarrier = require('font-carrier');
9
10
11// 十进制 转 16进制
12function decimal2Hex(n){
13 var hex = n.toString(16);
14 hex = '000'.substr(0, 3 - hex.length) + hex;
15 return hex;
16}
17
18// 生成 icon 对应的 content
19function generateIconContent(n){
20 return '&#xf' + decimal2Hex(n);
21}
22
23function mkdir(dir) {
24 if(!fs.existsSync(dir)) {
25 mkdir(path.dirname(dir));
26 fs.mkdirSync(dir);
27 }
28}
29
30/*
31* generate font files
32* 字体文件 md5
33*/
34exports.genarateFonts = function (opt, icons) {
35 var svgPath = opt._svgPath,
36 // output = opt.fontsOutput,
37 font = fontCarrier.create(),
38 svgsObj = {},
39 filePath,
40 iconContent;
41 icons.forEach(function(icon, index){
42 filePath = path.join(svgPath, icon + '.svg');
43 if(fs.existsSync(filePath)) {
44 iconContent = generateIconContent(index);
45 svgsObj[iconContent] = fs.readFileSync(filePath).toString();
46 } else {
47 fis.log.warning(filePath + ' ------ svg file does not exist!');
48 }
49
50 });
51
52 font.setSvg(svgsObj);
53
54 var outFontsContent = font.output({}),
55 outFileName = 'iconfont';
56
57 return {
58 content: outFontsContent,
59 subpath: opt.output + '/' + outFileName
60 };
61};
62
63/*
64* 根据icon生成对应的字体
65* 需要判断实际的svg(正则匹配到了不是icon的表达式)文件是否存在,否则会有多余样式
66 */
67exports.generateCss = function (opt, iconNames, start, step) {
68 var self = this,
69 pseudoClass = ~['after', 'before'].indexOf(opt.pseClass) ? opt.pseClass : 'after',
70 start = start || 0,
71 step = step || 1;
72
73 var content = [],
74 iconContent;
75 // 字体的引用和每个css的引入路径有关系
76
77 content.push('@font-face { ');
78 content.push('font-family: "mfont";');
79 content.push('src: url("' + opt._fontCdn.eot + '");'); // ie9
80 content.push('src: url("' + opt._fontCdn.eot + '?#iefix") format("embedded-opentype"),'); // ie6-8
81 content.push('url("' + opt._fontCdn.woff + '") format("woff"),'); // chrome、firefox
82 content.push('url("' + opt._fontCdn.ttf + '") format("truetype");}'); // chrome、firefox、opera、Safari, Android, iOS 4.2+
83
84 content.push('.icon-font{font-family:"mfont";font-size:16px;font-style:normal;font-weight: normal;font-variant: normal;text-transform: none;line-height: 1;position: relative;-webkit-font-smoothing: antialiased;}');
85 iconNames.forEach(function(iconName){
86 iconContent = generateIconContent(start++);
87 if (typeof iconContent !== 'undefined' && fs.existsSync(path.join(opt._svgPath, iconName + '.svg')) ) {
88 iconContent = iconContent.replace('&#xf', '\\f');
89 content.push('.i-' + iconName + ':' + pseudoClass + '{content: "' + iconContent + '";}');
90 }
91 });
92 return content.join('\r\n');
93};
94
95
96exports.exportCssFile = function(iconNames, pseClass, path) {
97 var content = this.generateCss(iconNames, pseClass);
98 fs.writeFileSync(path, content, 'utf-8');
99}