Skip to content

Commit

Permalink
Browsersync snippet regex for lookbehinds
Browse files Browse the repository at this point in the history
  • Loading branch information
fitztrev committed Sep 18, 2019
1 parent 719edb1 commit 19f26b5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/components/Browsersync.js
Expand Up @@ -34,6 +34,14 @@ class Browsersync {
return new BrowserSyncPlugin(this.config(), { reload: false });
}

/**
* The regex used to determine where the Browsersync
* javascript snippet is injected onto each page.
*/
regex() {
return /(<\/body>|<\/pre>)(?!.*(<\/body>|<\/pre>))/is;
}

/**
* Build the BrowserSync configuration.
*/
Expand All @@ -50,7 +58,7 @@ class Browsersync {
],
snippetOptions: {
rule: {
match: /(<\/body>|<\/pre>)/i,
match: this.regex(),
fn: function(snippet, match) {
return snippet + match;
}
Expand Down
18 changes: 18 additions & 0 deletions test/features/browsersync.js
@@ -1,5 +1,6 @@
import mix from './helpers/setup';
import mockRequire from 'mock-require';
import Browsersync from '../../src/components/Browsersync';

mockRequire(
'browser-sync-webpack-plugin',
Expand All @@ -21,3 +22,20 @@ test.serial.cb('it handles Browsersync reloading', t => {
);
});
});

test.serial.cb('it injects the snippet in the right place', t => {
let regex = new Browsersync().regex();

t.is(regex.exec(`<div></div>`), null);
t.is(regex.exec(`<body></body>`).index, 6);
t.is(regex.exec(`<pre></pre>`).index, 5);
t.is(regex.exec(`<body><pre></pre></body>`).index, 17);

let html = `<body>
<pre></pre>
<div></div>
<pre></pre>
</body>
`;
t.is(regex.exec(html).index, 75);
});

0 comments on commit 19f26b5

Please sign in to comment.