diff --git a/README.md b/README.md index fb4ae62..63cef31 100644 --- a/README.md +++ b/README.md @@ -40,8 +40,14 @@ rollup({ // too permissive exclude: 'node_modules/**', + // By default, occurences are only matched within word + // boundaries. Supply empty delimiters to replace every + // occurence of `foo` even in the middle of words, + // such as `barfoobar` + delimiters: [ '', '' ], + // To replace every occurence of `<@foo@>` instead of every - // occurence of `foo`, supply delimiters + // occurence of `\bfoo\b`, supply delimiters delimiters: [ '<@', '@>' ], // All other options are treated as `string: replacement` diff --git a/src/index.js b/src/index.js index be9258b..3a239db 100644 --- a/src/index.js +++ b/src/index.js @@ -5,9 +5,13 @@ function escape ( str ) { return str.replace( /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&' ); } +function boundaries ( str ) { + return str.replace( /[\b]/g, '\\b' ); +} + export default function replace ( options = {} ) { const values = options.values || options; - const delimiters = ( options.delimiters || [ '', '' ] ).map( escape ); + const delimiters = ( options.delimiters || [ '\b', '\b' ] ).map( escape ).map( boundaries ); const pattern = new RegExp( delimiters[0] + '(' + Object.keys( values ).join( '|' ) + ')' + delimiters[1], 'g' ); const filter = createFilter( options.include, options.exclude ); diff --git a/test/index.js b/test/index.js index 406f6dd..9f4f566 100644 --- a/test/index.js +++ b/test/index.js @@ -21,5 +21,23 @@ describe( 'rollup-plugin-replace', function () { }); }); + it( 'respects word boundaries', function () { + return rollup.rollup({ + entry: 'samples/basic/main.js', + plugins: [ + replace({ + ENV: "'production'", + BUILD: "'beta'" + }) + ] + }).then( function ( bundle ) { + const generated = bundle.generate(); + const code = generated.code; + + assert.ok( code.indexOf( "console.log( 'channel:', 'beta' )" ) !== -1 ); + assert.ok( code.indexOf( "...REBUILDING..." ) !== -1 ); + }); + }); + // TODO tests for delimiters, sourcemaps, etc }); diff --git a/test/samples/basic/main.js b/test/samples/basic/main.js index c48e748..0fd901c 100644 --- a/test/samples/basic/main.js +++ b/test/samples/basic/main.js @@ -3,3 +3,6 @@ if ( ENV !== 'production' ) { } else { console.log( 'running...' ); } + +console.log( 'channel:', BUILD ) +console.log( '...REBUILDING...' )