簡體   English   中英

Next.js 上基於 NODE_ENV 的條件 url

[英]Conditional url based on NODE_ENV on Next.js

有沒有辦法讓我根據我是在開發還是生產中設置一個 url?

目前我有一個帶有以下代碼的組件:

export default class Search extends Component {
    static async getInitialProps({ query: { location } }) {
        const res = await fetch(
            `http://localhost:3000/api/search?location=${location}`
        )
        const businesses = await res.json()
        return businesses
    }
...
}

我想要一些可以讓我做以下事情的東西:

export default class Search extends Component {
    static async getInitialProps({ query: { location } }) {
        let res
        if (environment is in developement) {
          res = await fetch(
            `http://localhost:3000/api/search?location=${location}`
          )

        } else if (environment is in production) {
          res = await fetch (
            `https://productionurl.now.sh/api/search?location=${location}`
          )
        }
        const businesses = await res.json()
        return businesses
    }
...
}

您可以使用NODE_ENV環境變量來做到這NODE_ENV 為了獲得良好的開發人員體驗,請設置如下配置文件:

/config/index.js

const dev = process.env.NODE_ENV !== 'production';

export const server = dev ? 'http://localhost:3000/api' : 'https://productionurl.now.sh/api';

然后您可以在整個應用程序的getInitialProps方法中使用它。

/組件/Search.js

import { server } from '../config';

// ...

static async getInitialProps({ query: { location } }) {
  const res = await fetch(`${server}/search?location=${location}`);
  const businesses = await res.json();
  return businesses;
}

確保在package.json構建腳本中設置了NODE_ENV變量,它應該看起來像這樣。

包.json

"scripts": {
  "build": "NODE_ENV=production next build",
},

是的,就像亞歷克斯貝內特所評論的那樣,使用 dotenv 應該適用於您的情況!

要設置它,

  1. 安裝 dotenv作為對你的 Node.js 項目的依賴npm install dotenv --save然后在你的應用程序中require('dotenv').config()

  2. 在您的項目的根目錄中創建一個名為.env的文件,其中包含您需要的<NAME>/<VALUE>格式的環境變量: MY_ENVIRONMENT=production

  3. 如果從托管服務器進行部署,請將<VALUE>更改production如果從本地主機進行部署,請將其更改development

  4. 設置完成后,您可以非常輕松地檢查代碼中加載的環境變量,如下所示(來自您的示例):

export default class Search extends Component {
    static async getInitialProps({ query: { location } }) {
        let res
        if (process.env.MY_ENVIRONMENT === 'development') {
          res = await fetch(
            `http://localhost:3000/api/search?location=${location}`
          )

        } else if (process.env.MY_ENVIRONMENT === 'production') {
          res = await fetch (
            `https://productionurl.now.sh/api/search?location=${location}`
          )
        }
        const businesses = await res.json()
        return businesses
    }
...
}

這是一個關於如何設置開發和生產的示例

const prodConfig = {
  publicRuntimeConfig: {
    API_ENDPOINT: 'http://google.com/api'
  }
}

const devConfig = {
  publicRuntimeConfig: {
    API_ENDPOINT: 'http://localhost:3000/api'
  }
}

module.exports = process.env.NODE_ENV === 'production ? prodConfig : devConfig

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM