Skip to content
This repository has been archived by the owner on Aug 4, 2021. It is now read-only.

Add support for matching word boundaries #10

Closed
wants to merge 1 commit into from
Closed
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
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
6 changes: 5 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down
18 changes: 18 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
});
3 changes: 3 additions & 0 deletions test/samples/basic/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ if ( ENV !== 'production' ) {
} else {
console.log( 'running...' );
}

console.log( 'channel:', BUILD )
console.log( '...REBUILDING...' )