I am using vue-template-compiler to change attribs in specific div, after updating I want to convert the ast's back to template string. How can I do it?
I want something like dom-serializer for vue. https://github.com/cheeriojs/dom-serializer#readme
const vtc = require('vue-template-compiler')
function parseVueComponent() {
const template = `
<template>
<div id="id_1" v-if="true">test</div>
<div>test2</div>
</template>
<script>
const a = 1
<script>
`
const compiled = vtc.compile(template)
compiled.ast.children.forEach(v => {
if(v.tag === 'div') {
v.attrsMap['v-if'] = false
}
console.log({ v :v })
})
// how to convert ast back to template string
}
parseVueComponent()
I just came across this question and I find it very valid. What you're trying to do is sometimes aspect-oriented programming. Based on some rules you'd like to add some functionality and have it implemented as a general concept.
In my case I'd like to parse the templates and replace code like <something acl="authenticated"...>
to <something v-if="authenticated"...>
and then to extend the script
section (or even add one if it doesn't exist) to define what authenticated
means. In my case, it'll be an import from a specific module, but it can be anything.
In Java, there is such a tool to do it. It's called AOP, so aspect-oriented programming, and runs during compilation. The advantage of AOP in Java is that it works directly against the AST.
To accomplish your goal you'll need to manually serialize the updated AST back to string as there is no stringify
for that. I might create an publish a package that does it but for now it is all on you.
Edit 15.02.2024:
Check out the vue-ast-serializer package. It's way not complete, but for the projects I have it was able to serialize the AST good enough. If there's something that you'll be missing please don't hesitate to open a Github issue and/or submit a PR. Thanks!
Edit 16.02.2024:
I've been working on an ACL/feature flag transformer so that I can manage my access rights and feature flags from a central location. As a result, I created vite-plugin-vue-sfc-transform. It accepts a transformer
function that gets the current filename and a list of sections.
I also noticed that using the original AST provided by Vue's SFC compiler is ugly because they don't store text nodes. It's better to use something like node-html-parser which also makes modifications super easy as it allows you to navigate the content of the <template>
as though it would be in the browser. Very convenient indeed.