From bbb91fbe595ced7f87ff66bbe92f9e766a56ec84 Mon Sep 17 00:00:00 2001 From: Smartin Date: Wed, 24 Nov 2021 18:05:45 +0100 Subject: [PATCH] add context to replace function --- README.md | 5 ++++- lib/processChunk.js | 2 +- lib/replace.js | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2497028..70d3d90 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,10 @@ module.exports = { loader: 'string-replace-loader', options: { search: '^Hello, (.*)!$', - replace: (match, p1, offset, string) => `Bonjour, ${p1.toUpperCase()}!`, + replace(match, p1, offset, string) { + console.log(`Replace "${match}" in file "${this.resource}".`) + return `Bonjour, ${p1.toUpperCase()}!` + }, flags: 'g' } } diff --git a/lib/processChunk.js b/lib/processChunk.js index 718df47..79fc341 100644 --- a/lib/processChunk.js +++ b/lib/processChunk.js @@ -8,7 +8,7 @@ function processChunk (source, map) { let newSource = source for (const options of optionsArray) { - newSource = replace(newSource, options) + newSource = replace(newSource, options, this) } this.callback(null, newSource, map) diff --git a/lib/replace.js b/lib/replace.js index b56b071..eb6cc26 100644 --- a/lib/replace.js +++ b/lib/replace.js @@ -1,5 +1,5 @@ -function replace (source, options) { +function replace (source, options, context) { const { replace, flags, strict } = options let search if (options.search instanceof RegExp) { @@ -15,7 +15,7 @@ function replace (source, options) { throw new Error('Replace failed (strict mode) : options.search and options.replace are required') } - const newSource = source.replace(search, replace) + const newSource = source.replace(search, typeof replace === 'function' ? replace.bind(context) : replace) if (strict && (newSource === source)) { throw new Error('Replace failed (strict mode) : ' + options.search + ' → ' + options.replace)