TommyD
TommyD

Reputation: 1043

Vue SFC add global Sass variables to all components

Im my webpack config I add a path

 "mixins": path.resolve(
        __dirname,
        "resources/assets/sass/mixins/mixins.scss"
      ),

Which means in all my single file components I use

<style lang='scss' scoped>
    @import '~variables';

This works fine but what I am finding is this file is used in 95% of components so the import really is unnecessary. I want these vars available everywhere.

How can I globally add my SASS to my single file components without the need for the import in every file?

Upvotes: 1

Views: 959

Answers (1)

Varit J Patel
Varit J Patel

Reputation: 3520

Well, Load your common CSS from Webpack and make it available globally for all the component. Webpack configurations are as below.

sass-loader also supports a data option which allows you to share common variables among all processed files without having to explicit import them

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        data: `
          @import "@/scss/_variables.scss";
          @import "@/scss/_mixins.scss";
        `
      }
    }
  }
};

In here, specifing the sass loader under the loaderOptions option. Just like that, all the code in those files will be available in the global scope. So from any component we can use it out of the box:

And now you can able to access the variable in your Vue SFC without importing it.

<style lang="scss">
.classroom {
  /* No need to import, it just works \o/ */
  background: $bg-classroom;
}
</style>

Reference Official Docs here

Hope this helps!

Upvotes: 2

Related Questions