【问题标题】:publicRuntimeConfig in next.config.js is always undefined in prod/stagingnext.config.js 中的 publicRuntimeConfig 在 prod/staging 中始终未定义
【发布时间】:2019-08-02 10:25:03
【问题描述】:

我正在将一个使用 next.js 的节点项目部署到我设置环境变量 MY_ENV 的 openshift。我已将 publicRuntimeConfig 配置添加到 next.config.js 以访问它的客户端。它在我的本地工作,但是当它的容器化和部署时 publicRuntimeConfigundefined

这是我在 next.config.js 中的配置

module.exports = {
  publicRuntimeConfig: { // Will be available on both server and client
      isProd: process.env.MY_ENV ? process.env.MY_ENV.includes('prod'): false,
      isStaging: process.env.MY_ENV ? process.env.MY_ENV.includes('staging') : false
    },
  webpack: (config, { dev }) => {
    const eslintRule = {
      test: /\.js$/,
      enforce: 'pre',
      exclude: /node_modules/,
      loader: 'eslint-loader',
      options: {
        emitWarning: dev,
      },
    };
    const cssRule = {
      test: /\.css$/,
      use: {
        loader: 'css-loader',
        options: {
          sourceMap: false,
          minimize: true,
        },
      },
    };

    config.node = {
      fs: 'empty'
    };

    config.module.rules.push(eslintRule);
    config.module.rules.push(cssRule);
    return config;
  }
};

这就是我试图在我的页面上获取 publicRuntimeConfig 的方式。

import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();

console.log(publicRuntimeConfig.isProd); //publicRuntimeConfig is undefined here. 

感谢任何帮助。

更新/修复

publicRuntimeConfig 在更高的环境中未定义,因为它不是要部署的包的一部分。

【问题讨论】:

    标签: javascript node.js reactjs openshift next.js


    【解决方案1】:

    undefined Error 是否出现在页面中?

    next/config 尝试getConfig 怎么样?

    import getConfig from 'next/config';
    
    const getNodeEnv = () => {
      const { publicRuntimeConfig } = getConfig();
    
      const isProd = publicRuntimeConfig.isProd || false;
      const isStaging = publicRuntimeConfig. isStaging || false;
    
      return { isProd, isStaging }
    };
    
    const env = getNodeEnv()
    
    console.log(env)
    

    【讨论】:

    • 是的,它发生在页面上,我添加了我如何使用它的问题。不确定我使用它的方式与您在这里使用的方式是否有区别。出于某种原因,如果我在本地设置环境变量,一切正常。
    • 我找不到你的不同之处。实际上,您的代码对我来说效果很好。我使用 next build 命令 defore deploy 进行生产。构建后,我将 pm2 start 与我的自定义文件 server.js 一起使用,但只是 next start 它可以工作。
    • 这就是我感到困惑的地方。我使用相同的,它在我的本地构建良好。我在想我可能在更高的环境中丢失了文件。你的答案和我如何获得 publicRuntimeConfig 有区别
    • 请检查并找出与我的 git 的不同之处。 github.com/kkangil/nextjs-mobx-boilerplate 我正在使用pm2 ecosystem。 process.env 变量是从ecosystem.config.js 设置的,我在utils/env 中分离了getNodeEnv 函数。最后我使用从getNodeEnv (pages/_error) 调用的 env
    • 谢谢伙计。我认为问题的一部分是文件未包含在正在部署到更高环境的包中
    猜你喜欢
    • 2020-03-20
    • 1970-01-01
    • 2021-11-21
    • 2011-12-16
    • 2021-01-31
    • 2020-04-11
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多