next.config.js 中的 publicRuntimeConfig 在 prod/staging 中始终未定义

Gri*_*pal 8 javascript node.js openshift reactjs next.js

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

这是我从 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;
  }
};
Run Code Online (Sandbox Code Playgroud)

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

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

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

Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。

更新/修复

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

kka*_*gil 6

是否undefined Error出现在页面中?

尝试getConfig从next/config怎么样?

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)
Run Code Online (Sandbox Code Playgroud)

  • 谢啦。我认为问题的一部分是文件未包含在部署到更高环境中的包中 (2认同)