简体   繁体   English

Next.js 将 NODE_ENV 传递给客户端

[英]Next.js pass NODE_ENV to client

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.这一定是一个常见问题,但我找不到任何好的解决方案。

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参考: 这里

Using Next's build-time configuration使用 Next 的构建时配置

@DarrylR already mentioned using next.config.js and Next's runtime configuration , but you can also use Next's build-time configuration . @DarrylR 已经提到使用next.config.js和 Next 的运行时配置,但您也可以使用 Next 的构建时配置

This lets you put the process.env.XXXX right into the code (as shown in step 3 below), and you don't have to import anything.这使您可以将process.env.XXXX直接放入代码中(如下面的第 3 步所示),并且您无需导入任何内容。 However, if you env variables should be set both when you build locally with Next.js and 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).但是,如果您在使用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_ENV for 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 time in now.json :如果您使用 ZEIT Now 进行部署,则可以在now.json设置构建时使用的环境变量

{
  "version": 2,
  "build": {
    "env": {
      "NODE_ENV": "production"
    }
  }
}

1.2 When running locally (optional) 1.2 本地运行时(可选)

If you want NODE_ENV to be set when running locally as well, this will not be set by now.json .如果你想NODE_ENV在本地以及运行时进行设置,这样就不会被设置now.json However you can set it in other ways, such as:但是,您可以通过其他方式设置它,例如:

$ NODE_ENV=production npm run build

or change the build script in package.json to或将package.json的构建脚本更改为

"build": "NODE_ENV=production next build"

You can of course also set NODE_ENV for other scripts than build if you want that.如果需要,您当然也可以为其他脚本设置NODE_ENV ,而不是 build。

2. Make Next inline value of process.env.NODE_ENV 2. 使process.env.NODE_ENV下一个内联值

Add this to the next.config.js as 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")
}

Another Easy solution:另一个简单的解决方案:

create 2 files on root folder:在根文件夹上创建 2 个文件:

.env.development
.env.production

inside add variables as you need, for example in .env.development file:在里面根据需要添加变量,例如在 .env.development 文件中:

NEXT_PUBLIC_ENV="development"

and in .env.production file:并在 .env.production 文件中:

NEXT_PUBLIC_ENV="production"

Then use it for example:然后使用它例如:

console.log('Version: ', process.env.NEXT_PUBLIC_ENV);

Since Next.js 9.4, NextJs has now built-in support for environment variables, which allows you to do the following using .env files:从 Next.js 9.4 开始,NextJs 现在内置了对环境变量的支持,这允许您使用 .env 文件执行以下操作:

An example .env.local:一个例子.env.local:

DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

If you want to expose the env variables to the client, you have to prefix the variable with NEXT_PUBLIC_ for example:如果要将 env 变量公开给客户端,则必须在变量前加上NEXT_PUBLIC_前缀,例如:

NEXT_PUBLIC_API_PORT=4000

If you want to use the variable, you can use it like this: process.env.NEXT_PUBLIC_API_PORT如果你想使用这个变量,你可以像这样使用它: process.env.NEXT_PUBLIC_API_PORT

For the documentation see here有关文档,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM