Simple css styles are no longer enough when it comes to more complex projects.
The linearity of the css is an obstacle compared to more complex structures, such as those provided for the compiled SCSS/SASS styles.
To include custom scss
in your project we can install sass-loader
.
npm i -D sass-loader@10.1.1 --save-exact && npm i -D sass
The version of sass-loader
needs to be exact and set at the latest 10.x.x
because the next one (11.0.0
) is using Webpack5, hence being a breaking change because Nuxt2 is only running on Webpack4 (https://github.com/webpack-contrib/sass-loader/releases).
When installed we to add that loader in our nuxt.config.js.
export default {
// ...
build: {
loaders: {
sass: {
implementation: require('sass'),
},
scss: {
implementation: require('sass'),
},
},
}
// ...
}
And later we can try in the component.
<template>
<div>
<span class="my-class">
Hello my class!
</span>
</div>
</template>
<style lang="scss" scoped>
div {
.my-class {
color: green;
}
}
</style>
Common SCSS resources
For common scss resources (like variables or mixins) you can install:
npm install --save-dev @nuxtjs/style-resources
And then import them into nuxt.config.js
, inside the modules
configuration.
modules: [
// ...
'@nuxtjs/style-resources',
]
And set them, still inside nuxt.config.js
.
styleResources: {
scss: [
'~/assets/scss/variables.scss',
]
}
That’s all.
Try it at home!