Skip to content

Commit c9f35af

Browse files
author
Valentyn
authored
Merge pull request #25 from hemnstill/master
Added strict mode
2 parents 86f0fbd + 3203e05 commit c9f35af

File tree

3 files changed

+266
-116
lines changed

3 files changed

+266
-116
lines changed

README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,31 @@ module.exports = {
8787
}
8888
```
8989

90+
### Strict mode replacement:
91+
92+
You can set strict mode to ensure that the replacement was done:
93+
94+
In your `webpack.config.js`:
95+
96+
```javascript
97+
module.exports = {
98+
// ...
99+
module: {
100+
loaders: [
101+
{
102+
test: /fileInWhichJQueryIsUndefined\.js$/,
103+
loader: 'string-replace',
104+
query: {
105+
search: 'jQuery',
106+
replace: 'window.$',
107+
strict: true
108+
}
109+
}
110+
]
111+
}
112+
}
113+
```
114+
90115
## Contributing:
91116

92117
Feel free to open issues to propose stuff and participate. Pull requests are also welcome.

index.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,21 @@ function processOptions(source, options) {
77
options.search = new RegExp(options.search, options.flags);
88
}
99

10-
source = source.replace(options.search, options.replace);
10+
newSource = source.replace(options.search, options.replace);
11+
if (options.strict === true && newSource === source) {
12+
throw new Error('Cannot replace ' + options.search + ' → ' + options.replace);
13+
}
1114
}
1215

13-
return source;
16+
if (options.strict === true && _.isUndefined(options.search)) {
17+
throw new Error('Cannot replace: search option is not defined → ' + JSON.stringify(options));
18+
}
19+
20+
if (options.strict === true && _.isUndefined(options.replace)) {
21+
throw new Error('Cannot replace: replace option is not defined → ' + JSON.stringify(options));
22+
}
23+
24+
return newSource;
1425
}
1526

1627
module.exports = function (source) {
@@ -20,6 +31,7 @@ module.exports = function (source) {
2031

2132
if (_.isArray(options.multiple)) {
2233
options.multiple.forEach(function (suboptions) {
34+
suboptions.strict = !_.isUndefined(suboptions.strict) ? suboptions.strict : options.strict;
2335
source = processOptions(source, suboptions);
2436
});
2537
} else {

0 commit comments

Comments
 (0)