vue.jssasslaravel-vue

Importing Scss into vue.js views


I've noticed that if I want to use my _variables.scss I have to import them in every Vue file. My question is, how can I check if I load the same styles multiple times or does Vue saves only once the same scss files on compiling?

This is my code in multiple view files.

<style lang="scss" scoped> @import '~@/abstracts/_variables.scss'; @import '~@/pages/_profile.scss'; </style>

I import _variables.scss in every view where I want to use my scss variables.


Solution

  • This depends on how you have your project setup, for example if you're using webpack you can do something like this where you have your CSS loaders setup:

    scss: generateLoaders('sass', {
      additionalData: `
          @import "@/styles/_variables.scss"
        `,
    }),
    

    Or if you have a vue.config.js you can do this:

    module.exports = {
      css: {
        loaderOptions: {
          sass: {
            additionalData: `
              @import "@/assets/scss/main.scss"
            `
          }
        }
      }
    }
    

    Then you will have access to this global SCSS file everywhere in your Vue application.

    Side note on the additionalData portion - that will depend on the version of sass loader you're using:

    For ^7.x.x use data, and for ^8.0.2 use prependData, finally for 9.0.0+ use additionalData