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

浪尽此生 提交于 2021-02-05 12:21:10

问题


I created a helpers.js under <project_root>/static folder

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

async function saveRegistration(pushSubscriptionObject) {

  let url = "";

  try {

    url = `${process.env.GATSBY_FUNCTION_URL_BASE}${process.env.GATSBY_FUNCTION_UPDATE_SUBSCRIPTION}`;

    console.log("using netlify config: ", url);

    console.log("--------updateSub() url--------", url);

  } catch (ex) {

    console.log("saveReg() catch block:", JSON.stringify(ex));

    return false;

  }

}

Here is my .env and .env.development (yes, they are same, because I’m testing what can make the env variables work):

GATSBY_FUNCTION_URL_BASE =http://localhost:34567/
GATSBY_FUNCTION_UPDATE_SUBSCRIPTION =updateSubscription

NETLIFY_FUNCTION_URL_BASE =http://localhost:34567/
NETLIFY_FUNCTION_ADD_SUBSCRIPTION =addSubscription
NETLIFY_FUNCTION_UPDATE_SUBSCRIPTION =updateSubscription

Here is my gatsby-config.js:

module.exports = {

  siteMetadata: {

    title: `Winston Fan's Blog`,

    description:

      ".....",

  },

  plugins: [

    "gatsby-plugin-react-helmet",

    "gatsby-plugin-sass",

    {

      // keep as first gatsby-source-filesystem plugin for gatsby image support

      resolve: "gatsby-source-filesystem",

      options: {

        path: `${__dirname}/static/img`,

        name: "uploads",

      },

    },

    {

      resolve: "gatsby-source-filesystem",

      options: {

        path: `${__dirname}/src/pages`,

        name: "pages",

      },

    },

    {

      resolve: "gatsby-source-filesystem",

      options: {

        path: `${__dirname}/src/img`,

        name: "images",

      },

    },

    {

      resolve: `gatsby-plugin-env-variables`,

      options: {

        allowList: ["NETLIFY_FUNCTION_URL_BASE", "NETLIFY_FUNCTION_ADD_SUBSCRIPTION", "NETLIFY_FUNCTION_UPDATE_SUBSCRIPTION"]

      },

    },

    "gatsby-plugin-sharp",

    "gatsby-transformer-sharp",

    {

      resolve: "gatsby-transformer-remark",

      options: {

        plugins: [

          {

            resolve: "gatsby-remark-relative-images",

            options: {

              name: "uploads",

              plugins: [

                {

                  resolve: "gatsby-remark-images",

                  options: {

                    // It's important to specify the maxWidth (in pixels) of

                    // the content container as this plugin uses this as the

                    // base for generating different widths of each image.

                    maxWidth: 2048,

                  },

                }

              ]

            },

          },

          {

            resolve: "gatsby-remark-copy-linked-files",

            options: {

              destinationDir: "static",

            },

          },

        ],

      },

    },

    {

      resolve: "gatsby-plugin-purgecss", // purges all unused/unreferenced css rules

      options: {

        develop: true, // Activates purging in npm run develop

        purgeOnly: ["/all.sass"], // applies purging only on the bulma css file

      },

    }, // must be after other CSS plugins

    {

      resolve: `gatsby-plugin-manifest`,

      options: {

        name: `AskWinston`,

        short_name: `HeyWinston`,

        start_url: `/`,

        background_color: `#FFF`,

        theme_color: `#FAE042`,

        display: `standalone`,

        icon: `src/img/wf-logo512.png`,

      },

    },

    {

      resolve: `gatsby-plugin-offline`,

      options: {

        appendScript: `src/sw.js`,

      },

    },

    {

      resolve: "gatsby-plugin-netlify-cms",

      options: {

        modulePath: `${__dirname}/src/cms/cms.js`,

      },

    },

    "gatsby-plugin-netlify" // make sure to keep it last in the array

  ],

};

However, no matter how I do it with environmental or OS variables, inside my helpers.js, I cannot get access to their values.

Update

I forgot to mention that I can use Environmental variables from client-side which is the gatsby-browser.js. So this makes me wondering why I cannot do the same for the helpers.js.


回答1:


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.



来源:https://stackoverflow.com/questions/63611042/how-to-use-environmental-or-os-variables-in-self-created-javascript-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!