diff --git a/lib/getOptionsArray.js b/lib/getOptionsArray.js index 4183a57..13360c3 100644 --- a/lib/getOptionsArray.js +++ b/lib/getOptionsArray.js @@ -26,6 +26,9 @@ const optionsSchema = { } ] }, + replaceAll: { + type: 'boolean' + }, flags: { type: 'string', }, @@ -39,6 +42,7 @@ const optionsSchema = { const defaultOptions = { search: null, replace: null, + replaceAll: false, flags: null, strict: false } diff --git a/lib/replace.js b/lib/replace.js index a8a144e..1216127 100644 --- a/lib/replace.js +++ b/lib/replace.js @@ -23,7 +23,9 @@ function replace (source, options, context) { throw new Error('Replace failed (strict mode) : options.search and options.replace are required') } - const newSource = source.replace(search, replace) + const newSource = options.replaceAll + ? source.replaceAll(search, replace) + : source.replace(search, replace) if (strict && (newSource === source)) { throw new Error('Replace failed (strict mode) : ' + options.search + ' → ' + options.replace) diff --git a/test/index.test.js b/test/index.test.js index d87b7b7..9bcf9ce 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -354,4 +354,53 @@ describe('Webpack replace loader ...', () => { } ) }) + + it('should replace only one occurrence', done => { + webpack(getTestWebPackConfig( + { + test: /\.js$/, + loader: '__this-loader', + options: { + search: 'abcd', + replace: 'efhg' + } + }), + (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.match(/abcd/g)).to.have.lengthOf(1); + expect(contents.match(/efhg/g)).to.have.lengthOf(1); + done() + }) + } + ) + }) + + it('should replace all occurrences', done => { + webpack(getTestWebPackConfig( + { + test: /\.js$/, + loader: '__this-loader', + options: { + search: 'abcd', + replace: 'efgh', + replaceAll: true + } + }), + (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).not.to.include('abcd') + expect(contents.match(/efgh/g)).to.have.lengthOf(2); + done() + }) + } + ) + }) }) diff --git a/test/source/entry.js b/test/source/entry.js index 1e9bbd2..b76048c 100644 --- a/test/source/entry.js +++ b/test/source/entry.js @@ -3,3 +3,8 @@ var bar = require('./bar'); var value = 'baz'; console.log(foo + bar + value); + +var first = 'abcd'; +var second = 'abcd' + +console.log(first + second);