Skip to content

Commit

Permalink
add context to replace function
Browse files Browse the repository at this point in the history
  • Loading branch information
smartin85 committed Nov 24, 2021
1 parent 5724411 commit bbb91fb
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 4 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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'
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/processChunk.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions lib/replace.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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)
Expand Down

0 comments on commit bbb91fb

Please sign in to comment.