diff --git a/README.md b/README.md index f4d9905..066fcaf 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ $ npm install --save-dev string-replace-loader ``` With release of 2.0.0 the loader is expected to be used in Node v4+ environment. -Support for Node v3 and lower was dropped, but you can install and use the loader version of 1.3.0 in older environments. +Support for Node v3 and lower was dropped, but you can install and use the loader version of 1.3.0 in older environments. ## Usage: @@ -120,6 +120,33 @@ module.exports = { } ``` +### Callback replacement: + +You can specify a callback function to dynamically replace a match. + +In your `webpack.config.js`: + + ```javascript +module.exports = { + // ... + module: { + rules: [ + { + test: /\.js$/, + loader: 'string-replace-loader', + options: { + search: '^Hello, (.*)!$', + replace: function(match, p1, offset, string){ + return 'Bonjour, ' + p1.toUpperCase() + '!!!'; + }, + flags: 'gi' + } + } + ] + } +} +``` + ## Contributing: Feel free to open issues to propose stuff and participate. Pull requests are also welcome. diff --git a/lib/getOptionsArray.js b/lib/getOptionsArray.js index 3e8cef7..5051e60 100644 --- a/lib/getOptionsArray.js +++ b/lib/getOptionsArray.js @@ -10,7 +10,10 @@ const optionsSchema = { type: 'string' }, replace: { - type: 'string' + 'anyOf': [ + { 'typeof': 'function' }, + { 'type': 'string' } + ] }, flags: { type: 'string', diff --git a/test/index.test.js b/test/index.test.js index 21e52c2..a334ee0 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -166,6 +166,30 @@ describe('Webpack replace loader ...', () => { ) }) + it('should replace when using callback', done => { + webpack(getTestWebPackConfig( + { + test: /\.js$/, + loader: '__this-loader', + options: { + search: 'var value', + replace: () => ('var a') + } + }), + (error, stats) => { + expect(error).to.equal(null) + + fs.readFile(outputFilePath, 'utf8', (error, contents) => { + expect(error).to.equal(null) + expect(contents).to.be.a('string') + expect(contents).to.not.include('var value') + expect(contents).to.include('var a') + done() + }) + } + ) + }) + it('should not throw error when cannot replace in single mode', done => { webpack(getTestWebPackConfig( {