If you develop a VueJS application, you might have come across the following problem: your CSS styles are working totally fine in development; but after building your project, some styles are wrong or missing.
This happened to me a few times and I want to save you from the trouble in this article.
A naive approach
Sometimes you need to customize the CSS class attached to an element. In my example I had events that had a different status (e.g. “confirmed” and “cancelled”). Each status has a different styling.
So naively I went my way and typed:
Note how I use string interpolation on the <div> element to dynamically change the CSS class depending on the eventStatus.
And this worked well in development on my machine. The confirmed events appeared in green (i.e. had the status-confirmed class) and the cancelled events appeared greyed out (i.e. had the status-cancelled class).
BUT it broke in my production build! All events had essentially no styling. What was going on?
If you know how vue-cli-service builds the production version of your web app, you quickly understand my mistake. Because “vue-cli-service build” scrambles the names of CSS classes. This is especially true, if you scoped your CSS — and this is good, because that way you won’t accidentally inherit CSS styles from elsewhere in your code. BUT creating CSS classes in such a dynamic way as we did isn’t recognized by this build magic!
The simple solution is to use the recommend (and cleaner) way to dynamically define CSS classes in VueJS:
And this works fine! It also works, if you use scoped CSS. Because now the build process either scrambles the full method name (which is fine) or nothing at all (which is also fine). In my initial, naive implementation, the build process only scrambled part of the CSS class identifier and ended up with something it could not reference elsewhere in my code.
So when using dynamic CSS classes, don’t use interpolated strings on the class attribute of HTML elements. Rather use a method, which generates your dynamic CSS class name.
Hope this helps! Cheers!