Skip to content

Commit bbb91fb

Browse files
committed
add context to replace function
1 parent 5724411 commit bbb91fb

File tree

3 files changed

+7
-4
lines changed

3 files changed

+7
-4
lines changed

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,10 @@ module.exports = {
133133
loader: 'string-replace-loader',
134134
options: {
135135
search: '^Hello, (.*)!$',
136-
replace: (match, p1, offset, string) => `Bonjour, ${p1.toUpperCase()}!`,
136+
replace(match, p1, offset, string) {
137+
console.log(`Replace "${match}" in file "${this.resource}".`)
138+
return `Bonjour, ${p1.toUpperCase()}!`
139+
},
137140
flags: 'g'
138141
}
139142
}

lib/processChunk.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ function processChunk (source, map) {
88
let newSource = source
99

1010
for (const options of optionsArray) {
11-
newSource = replace(newSource, options)
11+
newSource = replace(newSource, options, this)
1212
}
1313

1414
this.callback(null, newSource, map)

lib/replace.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
function replace (source, options) {
2+
function replace (source, options, context) {
33
const { replace, flags, strict } = options
44
let search
55
if (options.search instanceof RegExp) {
@@ -15,7 +15,7 @@ function replace (source, options) {
1515
throw new Error('Replace failed (strict mode) : options.search and options.replace are required')
1616
}
1717

18-
const newSource = source.replace(search, replace)
18+
const newSource = source.replace(search, typeof replace === 'function' ? replace.bind(context) : replace)
1919

2020
if (strict && (newSource === source)) {
2121
throw new Error('Replace failed (strict mode) : ' + options.search + ' → ' + options.replace)

0 commit comments

Comments
 (0)