有没有办法根据我是在开发还是生产中设置网址?
目前我有一个包含以下代码的组件:
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
环境变量执行此操作。为了获得良好的开发人员体验,请设置如下配置文件:
配置/索引.js
const dev = process.env.NODE_ENV !== 'production';
export const server = dev ? 'http://localhost:3000/api' : 'https://productionurl.now.sh/api';
然后,您可以在整个应用程序中的getInitialProps
方法中使用它。
组件/搜索.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",
},
下面是有关如何设置开发和生产的示例
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
是的,就像亚历克斯·贝内特评论的那样,使用 dotenv 应该适合您的情况!
要设置它,
-
将 dotenv 作为依赖项安装在 Node.js
npm install dotenv --save
项目上,然后在应用程序require('dotenv').config()
中需要它 -
在项目的根目录中创建一个名为
.env
的文件,其中包含您需要的以下<NAME>/<VALUE>
格式的环境变量:MY_ENVIRONMENT=production
. -
如果要从托管服务器部署,请将
<VALUE>
更改为production
,如果从本地主机部署,则更改为development
。 -
完成所有设置后,您可以非常轻松地检查代码中加载的环境变量,如下所示(来自您的示例(:
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
}
...
}