Using a configuration file for global variables in Nuxt is very simple, it just takes some steps to follow...
-
Step 1: Add
sass-loader
andnode-sass
to your project
using npm:
npm install --save-dev node-sass sass-loader
using yarn:
yarn add --dev node-sass sass-loader
-
Step 2: Adding the plugin
style-resources
to your project. If you don't know about plugins take a look in NuxtJS documentation. Also you can review the mentioned plugin right here.
using npm:
npm install --save-dev @nuxtjs/style-resources
using yarn:
yarn add --dev @nuxtjs/style-resources
-
Step 3: Adding to your
assets
directory a new sccs directory (this is where your global variable files will be stored, you can use as much as you like)
And my colors.scss
file looks like this
$white: #fff;
$black: #000;
$green: #43976c;
/* All the variables you want */
How we're going up to here? We're almost done! let's do this!
-
Step 4: Modify your
nuxt.config.js
file to map the new styles
export default {
//...
css: [
'~assets/scss/colors.scss'
],
//...
modules: [
'@nuxtjs/style-resources'
],
//You will have to add this new object if it doesn't exist already
styleResources: {
scss: ['./assets/scss/*.scss']
},
//...
}
We did it!! That's all! 👍 👍 Now we can use our new variables wherever we want without importing anything.
Example
// Don't forget to specify lang="scss"
<style lang="scss" scoped>
.my-css-class {
width: 90%;
height: 2px;
background-color: $green; // Here we are using the variable
border-radius: 5px;
}
</style>
Hope this was helpfull for you! I'll leave the original post where I learned from.
Thank you for reading!
Top comments (4)
Any way to get this to work with helper classes so we can use
@extend
in a components' style block? We use Bootstrap and need to keep the Vue markup clean.ie
.our-comp-name{
@extend .p-3, .p-lg-2l
}
fails as can't find the classes to extend.
Thank you very much for this article, helped me setup sass in Nuxt in few minutes.
Thank you very much!
Thank you very much. you really help me