How to use Environmental or OS variables in self-created JavaScript files

后端 未结 1 567
我在风中等你
我在风中等你 2021-01-29 10:43

I created a helpers.js under /static folder

Inside this JS file, I have method which needs access to the environmental/OS variabl

1条回答
  •  -上瘾入骨i
    2021-01-29 11:27

    You don't need plugins to access client-side nor server-side environment variables. First of all, I will try removing gatsby-plugin-env-variables.

    Despite of being client-side variables, putting them outside /src folder may cause some issues. I will try to add the following snippet in your gatsby-config.js (above the module exportation):

    require("dotenv").config({
      path: `.env.${process.env.NODE_ENV}`,
    })
    

    According to the documentation:

    Project environment variables that you defined in the .env.* files will NOT be immediately available in your Node.js scripts. To use those variables, use npm package dotenv to examine the active .env.* file and attach those values. dotenv is already a dependency of Gatsby, so you can require it in your gatsby-config.js or gatsby-node.js like this.

    0 讨论(0)
提交回复
热议问题