Skip to content

Commit

Permalink
some improvements to binding context
Browse files Browse the repository at this point in the history
  • Loading branch information
Va1 committed Nov 26, 2021
1 parent 437cf61 commit 2dd9941
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ module.exports = {
### Callback replacement

You can specify a callback function to have dynamic replacement values.
The context of this function will be the context of the loader.

In your `webpack.config.js`:

Expand Down
12 changes: 10 additions & 2 deletions lib/replace.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@

function replace (source, options, context) {
const { replace, flags, strict } = options
const { flags, strict } = options

let search
if (options.search instanceof RegExp) {
// if the `search` type is RegExp, we ignore `flags`
Expand All @@ -11,11 +12,18 @@ function replace (source, options, context) {
search = options.search
}

let replace
if (typeof options.replace === 'function') {
replace = options.replace.bind(context)
} else {
replace = options.replace
}

if (strict && (typeof search === 'undefined' || search === null || typeof replace === 'undefined' || replace === null)) {
throw new Error('Replace failed (strict mode) : options.search and options.replace are required')
}

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

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

0 comments on commit 2dd9941

Please sign in to comment.