UNPKG

1.59 kBJavaScriptView Raw
1'use strict';
2
3const jdfUtils = require('jdf-utils');
4const f = jdfUtils.file;
5const logger = require('jdf-log');
6const jdf = require('./jdf');
7const path = require('path');
8const vfs = require('./VFS/VirtualFileSystem');
9/**
10 * 直接修改vfs中的背景图为base64格式
11 * @param vNode vfs指向的一个文件节点
12 */
13function 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
43module.exports.init = function() {
44 logger.profile('base64');
45 vfs.queryFileByTargetType('css').forEach((item) => convert(item));
46 logger.profile('base64');
47}