Using Vue-cli, is it possible to build the CSS -into- the `dist/vue-COMPONENT_NAME.js` file?

Viewed 244

TLDR: Does anyone know of an elegant way to make sure a component injects its own <style>{...everything in ./dist/vue-COMPONENT_NAME.css}</style> element into the page, but only once? SSR friendly too?

I've been on the hunt for a good solution to this for over 2 days now; I'm building a Vue component that is likely to be used by mostly non-built, client side environments, included in the page via script tag:

<script src="https://unpkg.com/vue-COMPONENT_NAME/dist/vue-COMPONENT_NAME.js"></script>

And, normally you would just use a link tag to get the styles in there:

<link rel="stylesheet" href="https://unpkg.com/vue-COMPONENT_NAME/dist/vue-COMPONENT_NAME.css">

..but I would like remove the requirement to add the additional (possibly forgotten) link tag to the page. I would like for this component to be able to automatically inject its required styles into the page, so it is never displayed in an un-styled state.

This is a graphics focused component using a Canvas for display, and some of its internal logic is built on analyzing the clientBoundingRect of the top level DOM node - So having the styles that set its size and proportions at mount is imperative.

I am also planing on using this component myself via Nuxt, so I'm going to have to make sure that whatever solution I come to avoids the dreaded "The client-side rendered virtual DOM tree is not matching server-rendered content." error message.

So far, I have been loving how low-configuration the build with vue-cli has been:

vue build vue-COMPONENT_NAME.vue --prod --lib VueCOMPONENT

...but its output is always the two files:

./dist/vue-COMPONENT_NAME.js ./dist/vue-COMPONENT_NAME.css

Is there an argument or configuration prameter for vue-cli that would cause it to build the styles into ./dist/vue-COMPONENT_NAME.js? Has anyone done anything like this with vue-cli?

0 Answers
Related