-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
77 lines (66 loc) · 1.91 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
'use strict';
const debug = require('debug')('image-inliner');
const {getDataUriMapping} = require('./lib/image');
const DEFAULTS = {
assetPaths: [],
maxFileSize: 10240,
b64Svg: false,
strict: false,
filter: /^(mask(?:-image)?)|(list-style(?:-image)?)|(background(?:-image)?)|(content)|(cursor)/,
largeFileCallback: undefined,
svgoPlugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false,
},
},
},
],
};
const loop = (cb) => {
const matcher = /url\(\s*['"]*(?!['"]*data:)(.*?)['"]*\s*\)/gm;
return (decl) => {
let match;
while ((match = matcher.exec(decl.value)) !== null) {
cb({decl, url: match[match.length - 1]});
}
};
};
const escapeRegExp = (string) => string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
module.exports = (options_ = {}) => {
const options = {...DEFAULTS, ...options_};
options.assetPaths = Array.isArray(options.assetPaths)
? [...options.assetPaths, process.cwd()]
: [options.assetPaths, process.cwd()];
return {
postcssPlugin: 'postcss-image-inliner',
async Once(root) {
const urls = new Set([]);
const {filter} = options;
// Get urls
root.walkDecls(
filter,
loop(({url}) => urls.add(url))
);
const mapping = await getDataUriMapping([...urls], options);
root.walkDecls(
filter,
loop(({decl, url}) => {
if (mapping[url]) {
const regexp = new RegExp(`['"]?${escapeRegExp(url)}['"]?`, 'gm');
decl.value = decl.value.replace(regexp, `'${mapping[url]}'`);
debug(url, 'successfully replaced with ', mapping[url]);
} else {
debug(url, 'failed');
if (options_.strict) {
throw new Error(`No file found for ${url}`);
}
}
})
);
},
};
};
module.exports.postcss = true;