forked from webpack-contrib/svg-inline-loader
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
65 lines (54 loc) · 2.48 KB
/
index.js
File metadata and controls
65 lines (54 loc) · 2.48 KB
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
var simpleHTMLTokenizer = require('simple-html-tokenizer');
var tokenize = simpleHTMLTokenizer.tokenize;
var generate = simpleHTMLTokenizer.generate;
var loaderUtils = require('loader-utils');
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, loaderContext) {
// interpolate hashes in classPrefix
if(!!query && !!query.classPrefix) {
const name = query.classPrefix === true ? '[name]-' : query.classPrefix;
query.classPrefix = loaderUtils.interpolateName(loaderContext, name, {content: svgStr});
}
if (!!query && !!query.idPrefix) {
const id_name = query.idPrefix === true ? '[name]-' : query.idPrefix;
query.idPrefix = loaderUtils.interpolateName(loaderContext, 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, query));
}
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, this));
}
SVGInlineLoader.getExtractedSVG = getExtractedSVG;
SVGInlineLoader.conditions = conditions;
SVGInlineLoader.regexSequences = regexSequences;
module.exports = SVGInlineLoader;