Sharkey/webpack/loaders/replace.js

22 lines
724 B
JavaScript
Raw Normal View History

2018-02-15 17:53:54 +00:00
const loaderUtils = require('loader-utils');
2018-02-18 06:27:06 +00:00
function trim(text, g) {
return text.substring(1, text.length - (g ? 2 : 0));
2018-02-15 17:53:54 +00:00
}
module.exports = function(src) {
this.cacheable();
const options = loaderUtils.getOptions(this);
2018-02-15 18:23:10 +00:00
const search = options.search;
2018-02-18 06:27:06 +00:00
const g = search[search.length - 1] == 'g';
2018-04-14 16:04:40 +00:00
const file = this.resourcePath.replace(/\\/g, '/');
const replace = global[options.replace].bind(null, {
src: file
});
2018-02-15 18:23:10 +00:00
if (typeof search != 'string' || search.length == 0) console.error('invalid search');
if (typeof replace != 'function') console.error('invalid replacer:', replace, this.request);
2018-02-18 06:27:06 +00:00
src = src.replace(new RegExp(trim(search, g), g ? 'g' : ''), replace);
2018-02-15 17:53:54 +00:00
this.callback(null, src);
return src;
};