Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.1k views
in Technique[技术] by (71.8m points)

node.js - Azure static web app environment variable

I am trying to publish Gatsbyjs by Azure Static web app. I have a plugin (gatsby-source-contentful).

I need to pass variables like:

{
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: process.env.CONTENTFUL_SPACE_ID,
        accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
      },
},

Error:

Running 'npm run build'...


> [email protected] build /github/workspace
> gatsby build

success open and validate gatsby-configs - 0.021s
error Invalid plugin options for "gatsby-source-contentful":

- "accessToken" is required
- "spaceId" is required
not finished load plugins - 0.905s

Where can I pass this?

Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They are called environment variables. They are intended to store sensitive data such as tokens, identifiers, etc, and they shouldn't be pushed in your repository, so you should ignore them (in your .gitignore file).

By default, Gatsby creates 2 environments without noticing you, one for each compilation method:

  • gatsby develop: uses .env.development
  • gatsby build: uses .env.production

Note: you can change this behavior if needed to add your own environments using NODE_ENV custom commands.

So, to pass your data to your gatsby-config.js you just need to create two files (.env.development and .env.production) at the root of your project. Then, add the following snippet at the top of your gatsby-config.js:

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

Note: dotenv is already a dependency of Gatsby so you don't need to install it again

This will tell Gatsby where to take the environment variables.

You just remain to populate both environment files. Look for the credentials in Contentful and add them in the files using the sane naming than you've set in your gatsby-config.js:

CONTENTFUL_SPACE_ID=123456789 
CONTENTFUL_ACCESS_TOKEN=123456789 

Keep also in mind that when dealing with Azure, Netlify, AWS, or similar CI/CD tools, you'll need to provide to the server the same environment files to avoid a code-breaking when pushing the changes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...