close search bar

Sorry, not available in this language yet

close language selection

Today I Learned: Using SCSS in your Vue Components

Synopsys Editorial Team

Nov 13, 2018 / 1 min read

If you haven’t yet looked into Vue.js, it might be time to. The front-end framework is a powerful, progressive alternative to its main rivals, Facebook’s React and Google-backed Angular, and has been continuously gaining traction among the open source community.

One of the hallmarks of Vue is its use of single file components. It’s a pattern popular among the Vue community for a variety of reasons - among them the increased maintainability and reusability of components in medium to large projects. In Vue’s single file system, a component is defined by three tags: one for HTML, one for JavaScript, and one for styling. A very simple component may look like this:

Scss in vue components 1

In this way, the CSS for a given component lives alongside the rest of its code, and with the scoped attribute, will scope all style to only this component - preventing it from bleeding outwards and affecting global styling in unpredictable ways.

One might notice, however, that throughout much of Vue’s documentation and in countless tutorials, guides, and articles on all things Vue, the language used to this styling plain, vanilla CSS.  In a world where SCSS exists, with it’s support for variables, mixins, and nested styles, can we do better? Yes we can.

Styling your Vue components with SCSS is incredibly simple - provided you have the right configuration.



const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
mode: 'development',
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
]
}
]
},
plugins: [
new VueLoaderPlugin()
]
}

Above is an example webpack.config that makes use of vue-loader. You’ll want to install both the sass-loader and node-sass packages first, however.
npm install -D sass-loader node-sass
Once you’re configured, simply add a lang attribute to the style tags in your components:
SCSS in vue components 2

And you’re set! Enjoy all the features of SCSS in your Vue components.

Continue Reading

Explore Topics