Search code examples
javascriptnode.jsvue.jswebpacksass-loader

How can I set global Sass variables in Vue with Webpack?


These are the versions of Sass modules I use:

node-sass@^4

sass-loader@^7

I tried to set a global Sass variable in vue.config.js file:

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        prependData: `$primaryColor: #16A085;`
      }
    }
  }
}

But after running npm run dev, I get following error:

Module build failed:
     color: $primaryColor;
           ^
      Undefined variable: "$primaryColor".
      in C:\Users\tomek\Desktop\projekty\projectsBacketlist\noteTakingApp\frontend\noteTakkingApp\src\views\NoteEdit.vue (line 157, column 13)

 @ ./node_modules/vue-style-loader!./node_modules/css-loader?{"sourceMap":true}!./node_modules/vue-loader/lib/style-compiler?{"vue":true,"id":"data-v-b5e02554","scoped":false,"hasInlineConfig":false}!./node_modules/sass-loader/dist/cjs.js?{"sourceMap":true}!./node_modules/vue-loader/lib/selector.js?type=styles&index=0!./src/views/NoteEdit.vue 4:14-374 13:3-17:5 14:22-382
 @ ./src/views/NoteEdit.vue
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js

Solution

  • Your project is not a Vue CLI generated project, so vue.config.js would not be processed at all.

    In your case, you'd configure the Sass 7.x loaders in build/utils.js to pass the data option:

    exports.cssLoaders = function (options) {
      //...
    
      return {
        //...
        sass: generateLoaders('sass', { data: `$primaryColor: #16A085;` }),
        scss: generateLoaders('sass', { data: `$primaryColor: #16A085;` }),
      }
    }
    

    However, you should be aware of the note from the sass-loader docs:

    Please note: Since you're injecting code, this will break the source mappings in your entry file. Often there's a simpler solution than this, like multiple Sass entry files.