Skip to content

Commit

Permalink
(fix) adjust snip regex (sveltejs#216)
Browse files Browse the repository at this point in the history
Account for the script/style being inside a comment
Fixes sveltejs#212
  • Loading branch information
dummdidumm committed Apr 23, 2021
1 parent 61d8114 commit a441372
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/lib/snipTagContent.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
export const snippedTagContentAttribute = '✂prettier:content✂';

export function snipTagContent(tagName: string, source: string, placeholder = ''): string {
const regex = new RegExp(`<${tagName}([^]*?)>([^]*?)<\/${tagName}>`, 'g');
return source.replace(regex, (_, attributes, content) => {
const regex = new RegExp(`<!--[^]*?-->|<${tagName}([^]*?)>([^]*?)<\/${tagName}>`, 'g');
return source.replace(regex, (match, attributes, content) => {
if (match.startsWith('<!--')) {
return match;
}
const encodedContent = Buffer.from(content).toString('base64');
return `<${tagName}${attributes} ${snippedTagContentAttribute}="${encodedContent}">${placeholder}</${tagName}>`;
});
Expand Down
15 changes: 15 additions & 0 deletions test/printer/samples/style-script-commented-out.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!-- <script>
const a = true;
</script> -->
<script>
const a = true;
</script>

<!-- <style>
a { color: true }
</style> -->
<style>
a {
color: true;
}
</style>

0 comments on commit a441372

Please sign in to comment.