Nuxtjs how to add global environment variable in all sass files

Viewed 1489

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".

3 Answers

For Nuxt js:

build: {
   loaders: {
     scss: {
       additionalData: `$MAIN_COLOR: ${process.env.NUXT_MAIN_COLOR};`,
     },
   },
 },

In nuxt.config.js

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 + ';'
      }
    },
  }
}

For nuxt@2.15.3 and sass-loader@10.1.1 I have had to use this configuration (nuxt.config.js). Notice the use of sass instead of scss inside loaders:

export default {
  // ...,

  build: {
    loaders: {
      sass: {
        additionalData: `$main-color: ${process.env.MCOL}`
      }
    }
  }
}
Related