Skip to content

Commit b014594

Browse files
committed
support for function replacement w/ tests
1 parent c200a9f commit b014594

File tree

3 files changed

+38
-12
lines changed

3 files changed

+38
-12
lines changed

README.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ module.exports = {
9494
}
9595
```
9696

97-
### Replacement with callback
97+
### Callback replacement
9898

9999
You can specify a callback function to have dynamic replacement values.
100100

@@ -110,10 +110,8 @@ module.exports = {
110110
loader: 'string-replace-loader',
111111
options: {
112112
search: '^Hello, (.*)!$',
113-
replace: function(match, p1, offset, string){
114-
return 'Bonjour, ' + p1.toUpperCase() + '!!!';
115-
},
116-
flags: 'gi'
113+
replace: (match, p1, offset, string) => `Bonjour, ${p1.toUpperCase()}!`,
114+
flags: 'g'
117115
}
118116
}
119117
]

lib/getOptionsArray.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,13 @@ const optionsSchema = {
1010
type: 'string'
1111
},
1212
replace: {
13-
'anyOf': [
14-
{ 'typeof': 'function' },
15-
{ 'type': 'string' }
13+
anyOf: [
14+
{
15+
typeof: 'function'
16+
},
17+
{
18+
type: 'string'
19+
}
1620
]
1721
},
1822
flags: {

test/index.test.js

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,9 @@ describe('Webpack replace loader ...', () => {
5555
test: /\.js$/,
5656
loader: '__this-loader',
5757
options: {
58-
search: 'var VALUE = \'\.*\'',
59-
replace: 'var a = \'\'',
60-
flags: 'i'
58+
search: `var VALUE = '.*'`,
59+
replace: `var a = ''`,
60+
flags: 'ig'
6161
}
6262
}),
6363
(error, stats) => {
@@ -67,7 +67,7 @@ describe('Webpack replace loader ...', () => {
6767
expect(error).to.equal(null)
6868
expect(contents).to.be.a('string')
6969
expect(contents).to.not.include('var value')
70-
expect(contents).to.include('var a = \'\'')
70+
expect(contents).to.include(`var a = ''`)
7171
done()
7272
})
7373
}
@@ -107,6 +107,30 @@ describe('Webpack replace loader ...', () => {
107107
)
108108
})
109109

110+
it('should replace with function replace', done => {
111+
webpack(getTestWebPackConfig(
112+
{
113+
test: /\.js$/,
114+
loader: '__this-loader',
115+
options: {
116+
search: `var value = '(baz)'`,
117+
replace: (match, p1, offset, string) => `var a = '${p1.toUpperCase()}'`,
118+
flags: 'g'
119+
}
120+
}),
121+
(error, stats) => {
122+
expect(error).to.equal(null)
123+
124+
fs.readFile(outputFilePath, 'utf8', (error, contents) => {
125+
expect(error).to.equal(null)
126+
expect(contents).to.be.a('string')
127+
expect(contents).to.include(`var a = 'BAZ'`)
128+
done()
129+
})
130+
}
131+
)
132+
})
133+
110134
it('should replace using multiple queries', done => {
111135
webpack(getTestWebPackConfig(
112136
{

0 commit comments

Comments
 (0)