Skip to content

Added strict mode #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 31, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,31 @@ module.exports = {
}
```

### Strict mode replacement:

You can set strict mode to ensure that the replacement was done:

In your `webpack.config.js`:

```javascript
module.exports = {
// ...
module: {
loaders: [
{
test: /fileInWhichJQueryIsUndefined\.js$/,
loader: 'string-replace',
query: {
search: 'jQuery',
replace: 'window.$',
strict: true
}
}
]
}
}
```

## Contributing:

Feel free to open issues to propose stuff and participate. Pull requests are also welcome.
Expand Down
16 changes: 14 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,21 @@ function processOptions(source, options) {
options.search = new RegExp(options.search, options.flags);
}

source = source.replace(options.search, options.replace);
newSource = source.replace(options.search, options.replace);
if (options.strict === true && newSource === source) {
throw new Error('Cannot replace ' + options.search + ' → ' + options.replace);
}
}

return source;
if (options.strict === true && _.isUndefined(options.search)) {
throw new Error('Cannot replace: search option is not defined → ' + JSON.stringify(options));
}

if (options.strict === true && _.isUndefined(options.replace)) {
throw new Error('Cannot replace: replace option is not defined → ' + JSON.stringify(options));
}

return newSource;
}

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

if (_.isArray(options.multiple)) {
options.multiple.forEach(function (suboptions) {
suboptions.strict = !_.isUndefined(suboptions.strict) ? suboptions.strict : options.strict;
source = processOptions(source, suboptions);
});
} else {
Expand Down
Loading