Skip to content

Commit 758b647

Browse files
committed
perf: increase loader performance by avoiding re-parsing regexps
1 parent 90763c1 commit 758b647

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

index.js

+12-5
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@
44
*/
55
var loaderUtils = require('loader-utils');
66

7+
var REGEX_STYLE = /<style[\s\S]*?>[\s\S]*?<\/style>/i
8+
var REGEX_DECLARATION = /^\s*<\?xml [^>]*>\s*/i
9+
10+
var REGEX_DOUBLE_QUOTE = /"/g
11+
var REGEX_MULTIPLE_SPACES = /\s+/g
12+
var REGEX_UNSAFE_CHARS = /[{}\|\\\^~\[\]`"<>#%]/g
13+
714
module.exports = function(content) {
815
this.cacheable && this.cacheable();
916

@@ -15,10 +22,10 @@ module.exports = function(content) {
1522
if (limit <= 0 || content.length < limit) {
1623
var newContent = content.toString('utf8');
1724

18-
var hasStyleElement = /<style[\s\S]*?>[\s\S]*?<\/style>/i.test(newContent)
25+
var hasStyleElement = REGEX_STYLE.test(newContent)
1926

2027
if (query.stripdeclarations) {
21-
newContent = newContent.replace(/^\s*<\?xml [^>]*>\s*/i, "");
28+
newContent = newContent.replace(REGEX_DECLARATION, "");
2229
}
2330

2431
var data;
@@ -28,9 +35,9 @@ module.exports = function(content) {
2835
}
2936
data = "data:image/svg+xml;base64," + newContent.toString("base64");
3037
} else {
31-
newContent = newContent.replace(/"/g, "'");
32-
newContent = newContent.replace(/\s+/g, " ");
33-
newContent = newContent.replace(/[{}\|\\\^~\[\]`"<>#%]/g, function(match) {
38+
newContent = newContent.replace(REGEX_DOUBLE_QUOTE, "'");
39+
newContent = newContent.replace(REGEX_MULTIPLE_SPACES, " ");
40+
newContent = newContent.replace(REGEX_UNSAFE_CHARS, function(match) {
3441
return '%'+match[0].charCodeAt(0).toString(16).toUpperCase();
3542
});
3643

0 commit comments

Comments
 (0)