forked from webpack-contrib/svg-inline-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (59 loc) · 2.6 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
var simpleHTMLTokenizer = require('simple-html-tokenizer');
var tokenize = simpleHTMLTokenizer.tokenize;
var generate = simpleHTMLTokenizer.generate;
var loaderUtils = require('loader-utils');
var assign = require('object-assign');
var conditions = require('./lib/conditions');
var transformer = require('./lib/transformer');
// TODO: find better parser/tokenizer
var regexSequences = [
// Remove XML stuffs and comments
[/<\?xml[\s\S]*?>/gi, ""],
[/<!doctype[\s\S]*?>/gi, ""],
[/<!--.*-->/gi, ""],
// SVG XML -> HTML5
[/\<([A-Za-z]+)([^\>]*)\/\>/g, "<$1$2></$1>"], // convert self-closing XML SVG nodes to explicitly closed HTML5 SVG nodes
[/\s+/g, " "], // replace whitespace sequences with a single space
[/\> \</g, "><"] // remove whitespace between tags
];
function getExtractedSVG(svgStr, query) {
var config;
// interpolate hashes in classPrefix
if(!!query) {
config = assign({}, query);
if (!!config.classPrefix) {
const name = config.classPrefix === true ? '__[hash:base64:7]__' : config.classPrefix;
config.classPrefix = loaderUtils.interpolateName({}, name, { content: svgStr });
}
if (!!config.idPrefix) {
const id_name = config.idPrefix === true ? '__[hash:base64:7]__' : config.idPrefix;
config.idPrefix = loaderUtils.interpolateName({}, id_name, { content: svgStr });
}
}
// Clean-up XML crusts like comments and doctype, etc.
var tokens;
var cleanedUp = regexSequences.reduce(function (prev, regexSequence) {
return ''.replace.apply(prev, regexSequence);
}, svgStr).trim();
// Tokenize and filter attributes using `simpleHTMLTokenizer.tokenize(source)`.
try {
tokens = tokenize(cleanedUp);
} catch (e) {
// If tokenization has failed, return earlier with cleaned-up string
console.warn('svg-inline-loader: Tokenization has failed, please check SVG is correct.');
return cleanedUp;
}
// If the token is <svg> start-tag, then remove width and height attributes.
return generate(transformer.runTransform(tokens, config));
}
function SVGInlineLoader(content) {
this.cacheable && this.cacheable();
// this.value = content;
// Configuration
var query = loaderUtils.parseQuery(this.query);
return "module.exports = " + JSON.stringify(getExtractedSVG(content, query));
}
SVGInlineLoader.getExtractedSVG = getExtractedSVG;
SVGInlineLoader.conditions = conditions;
SVGInlineLoader.regexSequences = regexSequences;
module.exports = SVGInlineLoader;