Next.js将NODE_ENV传递给客户端

时间:2018-11-12 16:59:39

标签: javascript node.js reactjs environment-variables next.js

我正在使用Next.js构建一个React SSR应用。

我希望能够在客户端访问NODE_ENV,因为这将告诉我的应用程序要使用哪些API端点。

我正在努力为此找到一种体面的方法。第一次在服务器上呈现页面时,我想将NODE_ENV定义为窗口变量,然后在我进行API调用的辅助函数中,检查是否在服务器或客户端上调用了代码,并根据需要使用window或process.env变量。

有人对这个问题有很好的解决方案吗?这肯定是一个普遍的问题,但是我找不到任何好的解决方案。

3 个答案:

答案 0 :(得分:13)

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
  }
}

参考:here


2。使用babel插件将变量导入整个应用程序:

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

const env = require('./env-config.js')

module.exports = {
  presets: ['next/babel'],
  plugins: [['transform-define', env]]
}

index.js

export default () => (
  <div>Loading data from { process.env.BACKEND_URL }</div>
)

参考:here

3。使用next / config:

next.config.js

module.exports = {
  publicRuntimeConfig: {
    API_URL: process.env.API_URL
  }
}

index.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>
  }
}

参考:here

答案 1 :(得分:0)

使用Next的构建时配置

@DarrylR已经使用next.config.js和 下一个runtime configuration, 但您也可以使用Next的build-time configuration

这使您可以将process.env.XXXX放到代码中(如下面的第3步所示),而不必导入任何内容。但是,如果在使用Next.js在本地构建时以及在部署到ZEIT Now时都应设置env变量,则我不知道是否可以使用此方法将它们保存在一个文件中(请参见下面的步骤2)。

运行时配置文档建议您通常要使用构建时配置:

  

警告:通常,您希望使用构建时配置来提供配置。这样做的原因是运行时配置增加了渲染/初始化开销,并且automatic prerendering不兼容。


步骤:

1。为构建过程设置NODE_ENV

1.1使用ZEIT Now

如果使用ZEIT Now进行部署,则可以在now.json中设置env variables used at build time

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

1.2在本地运行时(可选)

如果还希望在本地运行时设置NODE_ENV,则now.json不会设置此值。 但是,您可以通过其他方式进行设置,例如:

$ NODE_ENV=production npm run build

或将package.json中的构建脚本更改为

"build": "NODE_ENV=production next build"

如果需要,您当然也可以为构建脚本以外的其他脚本设置NODE_ENV

2。使下一个内联值为process.env.NODE_ENV

按照here所述将其添加到next.config.js

module.exports = {
  env: {
    NODE_ENV: process.env.NODE_ENV
  }
};

3。在代码中使用

if (process.env.NODE_ENV === "production") {
  console.log("In production")
} else {
  console.log("Not in production")
}

答案 2 :(得分:-1)

另一种简单的解决方案:

在根文件夹上创建2个文件:

.env.development
.env.production

在内部根据需要添加变量,例如在.env.development文件中:

NEXT_PUBLIC_ENV="development"

和.env.production文件中的

NEXT_PUBLIC_ENV="production"

然后以它为例:

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