Ziad Akiki
Ziad Akiki

Reputation: 2680

VueJS - Import a global scss in all .vue components

I'm using Vue JS with ASP .NET Core, I started the project from this template on GitHub (not from Vue CLI). The project loads fine, but I'm willing to use SCSS so that I can include a global file containing variables and mixins across all the vue components.

The 'stone age' solution would be to include the file in every component template but this repeats the same contents across all components.

I then found that I can preload a global scss file using webpack, so I followed multiple documentations (here, here and here to name a few) but nothing seems to work. I still get 'undefined variable' once I try to use a variable inside a component like so:

<style lang="scss">
h1 {
    color: $danger;
}
</style>

Where $danger is defined in _variables.scss found at ./ClientApp/styles.

I tried to configure SASS loader as follows (~styles is an alias defined in the config):

      use: [
        'vue-style-loader',
        'css-loader',
        {
          loader: 'sass-loader',
          options: {
            data: `
              @import "~styles/_variables.scss";
            `
          }
        }
      ]

Even installing vue add style-resources-loader and configuring it in in vue.config.js like so:

const path = require('path');

module.exports = {
  css: {
    loaderOptions: {
      // pass options to sass-loader
      sass: {
        data: `@import "~styles/global.scss";`
      }
    }
  }
}

I'm starting to think that this have to do with how ASP.NET Core handles SPA applications or some misconfiguration of Webpack but I have no clue what to try next.

Upvotes: 1

Views: 1373

Answers (1)

Charleshaa
Charleshaa

Reputation: 2238

Given you tried to set it up with your first bit of code, I assume you are using vue-cli 2 and not 3.

If that is the case, then you need to modify the configuration for the vue-loader and not the sass loader.

In ./build/utils.js, you should add options to the generateLoaders() function as such:

return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less', {
      enableJavascript: true
    }),
    sass: generateLoaders('sass', {
      indentedSyntax: true
    }),
    scss: generateLoaders('sass', {
      data: `@import "${path.resolve(__dirname, "../src/your_file.scss")}";` // THIS LINE
    }),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
}

You will be able to use your SASS variables in any component without having to import it.

Upvotes: 2

Related Questions