Vue is an incredibly powerful front-end framework, and I much prefer it compared to Angular or React. Vue is like the best of both worlds. It combines some of my favorite parts of React and Angular into one lightweight, easy to learn framework and it’s gaining some serious traction on the internets. There is already a massive amount of libraries and components available that make working with Vue a lovely experience.
One thing that I really love about Vue is writing SASS directly in your components!
For those that don’t quite know what I’m talking about.. let’s take a quick look at your average Vue component:
Notice in the style tag there is a word, “scoped“. This means that all CSS in the <style> tag will only be applied to the current component. This can be a very handy feature when we want to apply unique styling to a specific part of our application.
Conversely, if you omit the scoped keyword then the styling will be applied to the entire application as you would assume.
But what happens if you write SASS instead of CSS? Well… it breaks your app, but don’t worry! The whole reason I wrote this article is to show you how to write SASS right in your component code!!
Vue uses Webpack to build everything and allows us to modify its configuration by including a webpack.config.js file in our Vue project’s root directory.
Before we do that, we need to install some dependencies by typing the following commands in your project’s root directory:
Please note: this tutorial assumes that you installed Vue using Vue-CLI. Vue alone requires a bit more configuration / setup than what is demonstrated herein. If you need some help, feel free to e-mail me at email@example.com
Once you’ve added the dependencies, you can include them in your project by adding the following code to your webpack.config.js file (if it’s not there, just create it and paste the following code in it)
In the example above, notice that we’ve defined a “rule” that tests for “.scss”, you could specify a different file format here and update the “use” array by replacing “sass-loader” with the CSS preprocessor of your choosing.
Remember how styling blocks were either scoped, or not? Well… in order to enable SASS syntax instead of CSS we’ll need to add the “lang” attribute to the <style> tag, and set the value to “scss” as shown below.
(Remember, you can use the keyword scoped to enforce styling locally.)
Of course, to include an external SCSS file you would need to import it into your root component like you would a normal CSS file.
Naturally, you would use “sass” instead of “scss” if you’re writing indentation syntax. However, I like using bracket syntax instead because it’s more like CSS3.
Well, there you have it folks.. something that took me 1 hour to figure out packed up in a blog article for you to read in 5 minutes 😂✌
For more information, check out the Vue documentation on CSS modules here: