Unable to set additional environment variable in Gatsby build

Viewed 912

I am trying to build Gatsby project with staging environment variable but it is always using production environment variables

I used this tutorial Environment Variables | Gatsby

This is my gatsby-config.js file

let activeEnv = process.env.ACTIVE_ENV || process.env.NODE_ENV || 
'development';

console.log(`Using environment config: '${activeEnv}'`);

require("dotenv").config({
  path: `.env.${activeEnv}`,
});

module.exports = { 
plugins: [
   {
     resolve: `gatsby-plugin-sass`,
     options: {
       precision: 8,
     },
   },
 ]
};

This is the command i am using to build

"build:staging": "set ACTIVE_ENV='staging' && gatsby build",

When i run the above command it show Using environment config: 'staging' but after build it uses production variables

My .env files .env files

After Running ACTIVE_ENV='staging' gatsby build i got this

$ ACTIVE_ENV='staging' gatsby build
success delete html and css files from previous builds — 0.058 s
⠁ Using environment config: 'staging'
{ API_URL: 'https://api.company.com/api/company/test',
  COMPANY_URL: 'https://company.test.com/test/' }
success open and validate gatsby-config — 0.011 s
info One or more of your plugins have changed since the last time you ran 
Gatsby. As a precaution, we're deleting your site's cache to ensure there's not any stale
data
success copy gatsby files — 0.044 s
success onPreBootstrap — 0.039 s
success source and transform nodes — 0.026 s
success building schema — 0.112 s
success createLayouts — 0.007 s
success createPages — 0.001 s
success createPagesStatefully — 0.082 s
success onPreExtractQueries — 0.001 s
success update schema — 0.072 s
success extract queries from components — 0.041 s
success run graphql queries — 0.015 s
success write out page data — 0.005 s
success write out redirect data — 0.001 s
success onPostBootstrap — 0.001 s

info bootstrap finished - 3.516 s

success Building CSS — 13.139 s
success Building production JavaScript bundles — 26.757 s
⢀ Building static HTML for pages{ API_URL: 
'https://api.company.com/api/company/prod',
  COMPANY_URL: 'https://company.test.com/prod/',
  NODE_ENV: 'production',
  PUBLIC_DIR: 'D:\\website/public' }
success Building static HTML for pages — 8.390 s
info Done building in 51.808 sec
1 Answers

i resolved this issue using cross-env package. Now it is working fine.

Here is the command

"build:staging": "cross-env ACTIVE_ENV=\"staging\" gatsby build",

Now when i run npm run build:staging it build using .env.staging

Related