Wrong CSS in VueJS in production

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.

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:

Note how I now DO NOT use string interpolation on the <div> element directly. Instead I use the interpolation in the Javascript code of the component. Only the resulting string is then used on the <div> element. (Btw: you could also use an object like {status-confirmed: true, status-cancelled: false}).

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!

Written by

Agile Coach, Business Innovator, Software Engineer, Musician

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store