1 | 'use strict';
|
2 |
|
3 | const jdfUtils = require('jdf-utils');
|
4 | const f = jdfUtils.file;
|
5 | const logger = require('jdf-log');
|
6 | const jdf = require('./jdf');
|
7 | const path = require('path');
|
8 | const vfs = require('./VFS/VirtualFileSystem');
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | function convert(vNode) {
|
14 | const regBackground = /background(?:-image)?:([\s\S]*?)(?:;|$)/gi;
|
15 | const regImgUrl = /url\s*\(\s*("(?:[^\\"\r\n\f]|\\[\s\S])*"|'(?:[^\\'\n\r\f]|\\[\s\S])*'|[^)}]+)\s*\)/i;
|
16 | const regIsBase64 = /[?&]__base64/i;
|
17 |
|
18 | const source = vNode.originPath;
|
19 | let content = vNode.targetContent;
|
20 | const background = content.match(regBackground);
|
21 |
|
22 | if (background) {
|
23 | logger.verbose(`base64: ${source}`);
|
24 | content = encodeURIComponent(content);
|
25 | background.forEach((item) => {
|
26 | const imgUrl = item.match(regImgUrl);
|
27 |
|
28 | if (imgUrl && imgUrl[0].match(regIsBase64)) {
|
29 | const bgImgPath = path.join(path.dirname(source), imgUrl[1].replace('?__base64', ''));
|
30 |
|
31 | if (f.exists(bgImgPath)) {
|
32 | const base64Encode = f.base64Encode(bgImgPath);
|
33 | content = content.replace(new RegExp(encodeURIComponent(imgUrl[1]), 'gi'), ('data:image/png;base64,' + base64Encode));
|
34 | }else{
|
35 | logger.error(bgImgPath + ' is not exist');
|
36 | }
|
37 | }
|
38 | });
|
39 | vNode.targetContent = decodeURIComponent(content);
|
40 | }
|
41 | }
|
42 |
|
43 | module.exports.init = function() {
|
44 | logger.profile('base64');
|
45 | vfs.queryFileByTargetType('css').forEach((item) => convert(item));
|
46 | logger.profile('base64');
|
47 | }
|