javascript Next.js 将 NODE_ENV 传递给客户端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53266814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Next.js pass NODE_ENV to client
提问by Hyman Wild
I'm building a React SSR App, using Next.js.
我正在使用 Next.js 构建一个 React SSR 应用程序。
I want to be able to access the NODE_ENV on the client side, as this will tell my app which API endpoints to use.
我希望能够在客户端访问 NODE_ENV,因为这将告诉我的应用程序要使用哪些 API 端点。
I'm struggling to find a decent approach for this. I'd like to define the NODE_ENV as a window variable when I first render the page on the server, and then in my helper function where I make the API call, I would check if the code is being called on the server or the client, and using the window or process.env variables as required.
我正在努力为此找到一个合适的方法。当我第一次在服务器上呈现页面时,我想将 NODE_ENV 定义为窗口变量,然后在我进行 API 调用的辅助函数中,我会检查代码是在服务器上还是在客户端上调用,并根据需要使用 window 或 process.env 变量。
Does anyone have a good solution for such a problem. It must be a common issue but I can't find any good solutions.
有没有人对这样的问题有很好的解决方案。这一定是一个常见问题,但我找不到任何好的解决方案。
回答by Darryl RN
1. You can include it in webpack configuration (using dotenv-webpack dependency):
1. 你可以将它包含在 webpack 配置中(使用 dotenv-webpack 依赖):
require('dotenv').config()
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
webpack: (config) => {
config.plugins = config.plugins || []
config.plugins = [
...config.plugins,
// Read the .env file
new Dotenv({
path: path.join(__dirname, '.env'),
systemvars: true
})
]
return config
}
}
Reference: here
参考:这里
2. using babel plugin to import the variable towards the entire app:
2. 使用 babel 插件将变量导入到整个应用程序:
env-config.js
env-config.js
const prod = process.env.NODE_ENV === 'production'
module.exports = {
'process.env.BACKEND_URL': prod ? 'https://api.example.com' : 'https://localhost:8080'
}
.babelrc.js
.babelrc.js
const env = require('./env-config.js')
module.exports = {
presets: ['next/babel'],
plugins: [['transform-define', env]]
}
index.js
索引.js
export default () => (
<div>Loading data from { process.env.BACKEND_URL }</div>
)
Reference: here
参考:这里
3. Using next/config:
3.使用next/config:
next.config.js
下一个.config.js
module.exports = {
publicRuntimeConfig: {
API_URL: process.env.API_URL
}
}
index.js
索引.js
import React from 'react'
import getConfig from 'next/config'
const {publicRuntimeConfig} = getConfig()
const {API_URL} = publicRuntimeConfig
export default class extends React.Component {
static async getInitialProps () {
// fetch(`${API_URL}/some-path`)
return {}
}
render () {
return <div>
The API_URL is {API_URL}
</div>
}
}
Reference: here
参考:这里
回答by ArneHugo
Using Next's build-time configuration
使用 Next 的构建时配置
@DarrylR already mentioned using next.config.jsand
Next's runtime configuration,
but you can also use Next's build-time configuration.
@DarrylR 已经提到 usingnext.config.js和 Next 的运行时配置,但您也可以使用 Next 的构建时配置。
This lets you put the process.env.XXXXright into the code (as shown in step 3 below), and you don't have to import anything. However, if you env variables should be set both when you build locally with Next.jsand when you deploy to ZEIT Now, I don't know if you can keep them in just one file using this method (see step 2 below).
这让您可以将process.env.XXXX权限放入代码中(如下面的第 3 步所示),并且您无需导入任何内容。但是,如果您在使用Next.js本地构建和部署到ZEIT Now时都应设置环境变量,我不知道您是否可以使用此方法将它们保存在一个文件中(请参阅下面的第 2 步)。
The runtime configuration docs suggest you normally want to use build-time configuration:
运行时配置文档建议您通常希望使用构建时配置:
Warning:Generally you want to use build-time configuration to provide your configuration. The reason for this is that runtime configuration adds rendering / initialization overhead and is incompatible with automatic prerendering.
警告:通常您希望使用构建时配置来提供您的配置。这样做的原因是运行时配置增加了渲染/初始化开销并且与自动预渲染不兼容。
Steps:
脚步:
1. Set NODE_ENVfor build process
1. 设置NODE_ENV构建过程
1.1 Using ZEIT Now
1.1立即使用ZEIT
If you deploy using ZEIT Now, you can set the env variables used at build timein now.json:
如果部署使用现在ZEIT,您可以设置在构建时使用的ENV变量中now.json:
{
"version": 2,
"build": {
"env": {
"NODE_ENV": "production"
}
}
}
1.2 When running locally (optional)
1.2 本地运行时(可选)
If you want NODE_ENVto be set when running locally as well, this will not be set by now.json.
However you can set it in other ways, such as:
如果您也想NODE_ENV在本地运行时进行设置,则不会由now.json. 但是,您可以通过其他方式设置它,例如:
$ NODE_ENV=production npm run build
or change the build script in package.jsonto
或将构建脚本更改package.json为
"build": "NODE_ENV=production next build"
You can of course also set NODE_ENVfor other scripts than build if you want that.
如果需要,您当然也可以为NODE_ENV构建以外的其他脚本进行设置。
2. Make Next inline value of process.env.NODE_ENV
2.使下一个内联值 process.env.NODE_ENV
Add this to the next.config.jsas described here:
将其添加到此处next.config.js所述:
module.exports = {
env: {
NODE_ENV: process.env.NODE_ENV
}
};
3. Use in code
3.在代码中使用
if (process.env.NODE_ENV === "production") {
console.log("In production")
} else {
console.log("Not in production")
}

