Search code examples
vue.jssassnuxt.jsnode-sass

Nuxtjs how to add global environment variable in all sass files


I want to load an environment variable in all my sass/scss files.

What I have done so far in nuxt.config.js:

export default {
  ...
  loaders: {
    scss: {
      data: '$myenv: ' + process.env.MY_ENV + ';'
    }
  }
}

and I got this error in mystyle.scss:

Undefined variable: "$myenv".


Solution

  • The loaders config belongs under the build property (not the root as you have it). If your project was generated with create-nuxt-app, the default nuxt.config.js already contains a build property at the bottom of the object, so you could move your loaders config into that property.

    Example (tested with Nuxt CLI v2.12.2):

    // nuxt.config.js
    export default {
      build: {
        loaders: {
          scss: {
            data: '$myenv: ' + process.env.MY_ENV + ';'
    
            // use `prependData` for sass-loader > 7.x
            //prependData: '$myenv: ' + process.env.MY_ENV + ';'
          }
        },
      }
    }