Skip to content

Commit

Permalink
perf: increase loader performance by avoiding re-parsing regexps
Browse files Browse the repository at this point in the history
  • Loading branch information
bhovhannes committed Jun 16, 2019
1 parent 90763c1 commit 758b647
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
*/
var loaderUtils = require('loader-utils');

var REGEX_STYLE = /<style[\s\S]*?>[\s\S]*?<\/style>/i
var REGEX_DECLARATION = /^\s*<\?xml [^>]*>\s*/i

var REGEX_DOUBLE_QUOTE = /"/g
var REGEX_MULTIPLE_SPACES = /\s+/g
var REGEX_UNSAFE_CHARS = /[{}\|\\\^~\[\]`"<>#%]/g

module.exports = function(content) {
this.cacheable && this.cacheable();

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

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

if (query.stripdeclarations) {
newContent = newContent.replace(/^\s*<\?xml [^>]*>\s*/i, "");
newContent = newContent.replace(REGEX_DECLARATION, "");
}

var data;
Expand All @@ -28,9 +35,9 @@ module.exports = function(content) {
}
data = "data:image/svg+xml;base64," + newContent.toString("base64");
} else {
newContent = newContent.replace(/"/g, "'");
newContent = newContent.replace(/\s+/g, " ");
newContent = newContent.replace(/[{}\|\\\^~\[\]`"<>#%]/g, function(match) {
newContent = newContent.replace(REGEX_DOUBLE_QUOTE, "'");
newContent = newContent.replace(REGEX_MULTIPLE_SPACES, " ");
newContent = newContent.replace(REGEX_UNSAFE_CHARS, function(match) {
return '%'+match[0].charCodeAt(0).toString(16).toUpperCase();
});

Expand Down

0 comments on commit 758b647

Please sign in to comment.