-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
336 lines (294 loc) · 9.87 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
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
const path = require("path");
const promisify = require("util").promisify;
const fs = require("fs-extra");
const revHash = require('rev-hash');
const spritesmith = promisify(require("spritesmith").run);
const SVGSpriter = require("svg-sprite");
const postcss = require("postcss");
var SVG_CONFIG = {
mode: {
css: {
dimensions: true,
bust: false,
layout: 'vertical',
render: {
scss: true
}
}
},
shape: {
id: {
generator: function (name, file) {
return file.path;
}
},
transform: ['svgo'],
}
};
function isdelProp(prop) {
return !!~[
"width",
"height",
"background-size",
"background-position"
].indexOf(prop);
}
function getUrl(url) {
try {
url = url.match(/url\((?:['"])?([^\)'"]+)(?:['"])?\)/)[1];
} catch (e) {}
return url;
}
function getDpr(url) {
let dpr;
try {
dpr = url.match(/@(\d)x/)[1];
} catch (e) {}
return dpr;
}
/* 将图片 url 按目录进行分组 */
function groupingURL(src) {
let groupSrc = {
img: [],
svg: []
};
let dir = new Set();
src.forEach(item => {
path.dirname(item) && dir.add(path.dirname(item));
});
let i = 0;
dir.forEach((value, key) => {
groupSrc.img[i] = [];
groupSrc.svg[i] = [];
src.forEach(item => {
if (path.dirname(item) === value) {
if (path.extname(item) === ".svg") {
groupSrc.svg[i].push(item);
} else {
groupSrc.img[i].push(item);
}
}
});
i++;
});
groupSrc.img = groupSrc.img.filter(n => n.length && n);
groupSrc.svg = groupSrc.svg.filter(n => n.length && n);
return groupSrc;
}
function appendObject(target, sources) {
Object.keys(target).forEach(key => {
target[key] = Object.assign(target[key], sources);
});
return target;
}
function getDir(url, outputPath, ext) {
let dirname = path.dirname(url);
dirname = dirname !== '.' ? dirname : 'sprite'
return path.join(
outputPath,
dirname
.split(path.sep)
.join("_")
.replace(/\.+/g, "") +
"." + ext
)
}
function hashedFilename(url, hash, revision) {
if (hash && revision === 'filename') {
let ext = path.extname(url)
url = url.replace(ext, '.' + hash + ext)
}
return url
}
module.exports = postcss.plugin("postcss-sprite", (options = {}) => {
let {
baseSize = 16,
unit = 'px',
imgPath = "../img/",
sliceDir = "slice",
spriteDir = "sprite",
spriteDisplay = "../img/sprite",
filter = url => ~url.indexOf(sliceDir + "/"),
replaceUrl,
spritesmithOptions = {},
revision = 'query'
} = options;
replaceUrl || (replaceUrl = spriteName => spriteDisplay + spriteName);
let sourcePath = imgPath + sliceDir + "/",
outputPath = path.resolve(imgPath + spriteDir);
return root => {
let rules = [];
let src = [];
let groupSrc = [];
root.walkRules(rule => {
rule.walkDecls(/background-image/, decl => {
// 提取图片 url
let url = getUrl(decl.value);
if (!filter(url)) {
return;
}
url = url.split(sliceDir + "/")[1];
if (src.indexOf(url) == -1) {
// 去重复
src.push(url);
}
rules.push(rule);
});
});
if (src.length == 0) {
return;
}
groupSrc = groupingURL(src);
let spritePromises = [];
let spriteNames = {
img: [],
svg: []
};
let spriteSoordinates = {};
svgConfig = SVG_CONFIG;
groupSrc.img.forEach((spriteItem, index) => {
spriteNames.img.push(
getDir(spriteItem[0], outputPath, 'png')
);
spritePromises.push(
spritesmith(
Object.assign({
src: spriteItem.map(url => path.resolve(sourcePath, url))
},
spritesmithOptions
)
)
);
});
// svg sprite
groupSrc.svg.forEach((spriteItem, index) => {
spriteNames.svg.push(
getDir(spriteItem[0], outputPath, 'svg')
);
let svgSpriter = new SVGSpriter(svgConfig);
spriteItem.forEach(url => {
svgSpriter.add(
path.resolve(sourcePath, url),
null,
fs.readFileSync(path.resolve(sourcePath, url), {
encoding: "utf-8"
})
);
});
svgSpriter.compile(function (error, result, data) {
let rev = revHash(result.css.sprite.contents);
let fileName = hashedFilename(spriteNames.svg[index], rev, revision);
let svgFile = result.css.sprite.contents || '';
svgFile = svgFile.toString().replace(/id=\"[^\"]*\.svg\"\s?/gi, '')
// 保存 svg sprite 到 sprite 目录
fs.outputFileSync(
fileName,
svgFile
);
data.css.shapes.forEach(item => {
spriteSoordinates[item.name] = {
x: item.position.absolute.x * -1,
y: item.position.absolute.y * -1,
width: item.width.inner || item.width.outer,
height: item.height.inner || item.height.outer,
spriteWidth: data.css.spriteWidth,
spriteHeight: data.css.spriteHeight,
spriteName: fileName,
rev: rev
}
})
});
});
return Promise.all(spritePromises)
.then(result => {
result.forEach(async (item, index) => {
let rev = revHash(item.image);
let fileName = hashedFilename(spriteNames.img[index], rev, revision);
// 保存 image sprite 到 sprite 目录
fs.outputFileSync(
fileName,
item.image
);
Object.assign(
spriteSoordinates,
appendObject(item.coordinates, {
spriteWidth: item.properties.width,
spriteHeight: item.properties.height,
spriteName: fileName,
rev: rev
})
);
});
return Promise.resolve(spriteSoordinates);
})
.then(async result => {
// 先删除
rules.forEach(rule => {
rule.walkDecls(decl => {
let prop = decl.prop;
if (isdelProp(prop)) {
decl.remove();
}
});
});
// 再添加
rules.forEach(rule => {
rule.walkDecls(decl => {
let prop = decl.prop;
if (prop != "background-image") {
return;
}
let url = decl.value;
let dpr = getDpr(url);
url = getUrl(url).split(sliceDir + "/")[1];
let {
width: w,
height: h,
x,
y,
spriteWidth,
spriteHeight,
spriteName,
rev
} = result[path.resolve(sourcePath, url)];
let size = dpr || 1;
if (unit === 'rem') {
size = (dpr || 1) * baseSize;
}
if (size > 1) {
w /= size;
h /= size;
x /= size;
y /= size;
spriteWidth /= size;
spriteHeight /= size;
}
let _url = replaceUrl(path.basename(spriteName));
if (revision && revision == 'query') {
_url += `?v=${rev}`;
}
decl.value = `url("${_url}")`;
rule.insertAfter(0, {
prop: "width",
value: `${w}${unit}`
})
.insertAfter(1, {
prop: "height",
value: `${h}${unit}`
})
.insertAfter(2, {
prop: "background-position",
value: `${-x}${unit} ${-y}${unit}`
})
.insertAfter(3, {
prop: "background-size",
value: `${spriteWidth}${unit} auto`
});
});
});
})
.catch(error => {
console.log("error", error);
});
};
});