Senior LevelVue JS
How do you write a custom Vue template compiler AST transform plugin to modify compilation output?
❓ Interview Prompt: Explain Vue template compiler AST transformation, nodeTransforms array, traversing AST Element nodes, and stripping test-id attributes.
The Vue 3 template compiler parses HTML templates into an Abstract Syntax Tree (AST) before generating render functions.
Custom AST Transform Plugins:
By providing custom 'nodeTransforms' functions to '@vue/compiler-dom' (or via 'vite-plugin-vue' options), you can inspect and transform AST nodes at build time (e.g. automatically stripping 'data-testid' attributes in production builds).
Code Implementation Example
javascript
// vite.config.js — Custom AST Transform Plugin stripping data-testid in production
import vue from '@vitejs/plugin-vue';
export default {
plugins: [
vue({
template: {
compilerOptions: {
nodeTransforms: [
(node) => {
if (node.type === 1 /* Element Node */) {
// Strip data-testid attributes during production compilation!
node.props = node.props.filter(p => p.name !== 'data-testid');
}
}
]
}
}
})
]
};💡Custom Vue compiler AST transform plugin stripping data-testid attributes at build time.
🎯 Interview Key Takeaway
Write custom compiler nodeTransforms plugins to manipulate the Vue template AST at build time.
#Compiler#AST#Build Plugins#Senior
Back to all Vue JS Questions→