Skip to content

Instantly share code, notes, and snippets.

@sw-yx

sw-yx/stringify.ts

Created Jun 6, 2020
Embed
What would you like to do?
JSON stringify replacer (no circular deps) pretty printer
import parse5 from 'parse5'
var src = `
{#if name}
<script>
console.log('not top level')
</script>
{/if}
<ul>
{#each cats as cat}
<script>
console.log('not top level')
</script>
{/each}
</ul>
{#await promise}
<script>
console.log('not top level')
</script>
{:then number}
<script>
console.log('not top level')
</script>
{:catch error}
<script>
console.log('not top level')
</script>
{/await}
<p>{@html <script> consolelog('not top level')</script>}</p>
<!-- p{ color: blue; }</script> -->
<!--<script lang="scss">
p{ color: blue; }
</script> -->
<scrit>blah</scrit>
<script>top level script</script>
`
var abc = parse5.parseFragment(src)
const fs = require('fs')
const path = require('path')
var cache: any = []
fs.writeFileSync('temp.json', JSON.stringify(abc, replacer, 2))
function replacer(key: any, value: any) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment