I have a Vue ^2.7.15 application running on Vite ^4.5.0. When I run a dev server, <style>
tags of each component are added into the <head>
element, for example:
<style type="text/css" data-vite-dev-id="/src/components/MyButton.vue?vue&type=style&index=-100&scoped=fc7ab1b1&lang.scss"">
/* CSS rules */
</style>
I would like to transform this tag before it gets appended to the DOM. How can I achieve this?
I have tried writing a vite plugin, however nothing different happens:
export default function myPlugin() {
return {
name: 'myPlugin',
enforce: 'post',
install() {
if (isDevMode) {
const originalAppendChild = document.head.appendChild;
document.head.appendChild = function (element) {
if (element.tagName === 'STYLE') {
element.setAttribute('test-attribute', 'test-value');
}
return originalAppendChild.call(document.head, element);
};
}
},
transform(code, id) {
if (!/vue&type=style/.test(id)) return;
return {
code: code.replace(
/(<style)/g,
'$1 <style test-attribute="test-value">'
),
map: null
};
}
};
}
Is there any way to achieve this? Thank you.
1