Skip to content

Commit

Permalink
Fix: just replace javascript in html (closes #70 (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
JPeer264 committed Feb 2, 2019
1 parent 6905a37 commit b4f3c9e
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 3 deletions.
26 changes: 23 additions & 3 deletions lib/replace/html.js
Expand Up @@ -34,9 +34,29 @@ const replaceHtml = (code, opts = {}) => {
traverse(ast, {
pre: (node) => {
// rename <script> tags
if (node.parentNode && node.parentNode.tagName === 'script') {
// eslint-disable-next-line no-param-reassign
node.value = replaceJs(node.value, options.espreeOptions);
if (
node.parentNode
&& node.parentNode.tagName === 'script'
) {
const hasAnyAttrs = node.parentNode.attrs.length === 0;
const hasType = node.parentNode.attrs.some(attr => attr.name === 'type');
const hasTypeAndJavaScript = (
node.parentNode.attrs.some(attr => (
attr.name === 'type'
&& (
attr.value === 'application/javascript'
|| attr.value === 'module'
)
))
);

// should just go inside if it is either
// no type
// type set to application/json || module
if (hasAnyAttrs || !hasType || hasTypeAndJavaScript) {
// eslint-disable-next-line no-param-reassign
node.value = replaceJs(node.value, options.espreeOptions);
}
}

// rename <style> tags
Expand Down
46 changes: 46 additions & 0 deletions test/replace.html.js
Expand Up @@ -152,3 +152,49 @@ test('should replace escaped selectors | issue #67',
'<table class="test selector:some-thing" id="id"></table>',
'<table class="test a" id="id"></table>',
);

test('should replace javascript',
replaceHtmlMacro,
['.selector', '.another-selector'],
`
<div class="selector another-selector">
<script data-something="data">
const a = "selector";
</script>
</div>
`,
`
<div class="a b">
<script data-something="data">
const a = "a";
</script>
</div>
`,
);

test('should ignore JSON | issue #70',
replaceHtmlMacro,
['.selector', '.another-selector'],
`
<div class="selector another-selector">
<script type="application/json">
{
"duration": "0.4s",
"shouldNotReplace": "another-selector",
"delay": "0.4s"
}
</script>
</div>
`,
`
<div class="a b">
<script type="application/json">
{
"duration": "0.4s",
"shouldNotReplace": "another-selector",
"delay": "0.4s"
}
</script>
</div>
`,
);

0 comments on commit b4f3c9e

Please sign in to comment.