如何在自行创建的JavaScript文件中使用环境变量或操作系统变量

时间:2020-08-27 07:21:22

标签: gatsby netlify netlify-cms

我在<project_root>/static文件夹下创建了一个helpers.js

enter image description here

在此JS文件中,我有需要访问环境/ OS变量的方法。

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;

  }

}

这是我的.env和.env.development(是的,它们是相同的,因为我正在测试什么可以使env变量起作用):

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

这是我的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

  ],

};

但是,无论我如何使用helpers.js中的环境变量或OS变量,都无法访问它们的值。

更新

我忘了提到我可以从客户端使用gatsby-browser.js的环境变量。所以这让我想知道为什么我不能对helpers.js做同样的事情。

1 个答案:

答案 0 :(得分:0)

您不需要插件即可访问客户端或服务器端环境变量。首先,我将尝试删除gatsby-plugin-env-variables

尽管它们是客户端变量,但是将它们放在/src文件夹之外可能会导致一些问题。我将尝试在您的gatsby-config.js中添加以下代码段(在模块导出上方):

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

根据文档:

您在.env.*文件中定义的项目环境变量 在您的Node.js脚本中不会立即可用。使用 这些变量,请使用npm软件包dotenv检查活动的.env.* 文件并附加这些值。 dotenv已经是 盖茨比,因此您可以在gatsby-config.jsgatsby-node.js这样。