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

问题描述 投票:2回答:1

我正在部署一个节点项目,该项目使用next.js进行openshift设置环境变量MY_ENV。我已将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. 

任何帮助表示赞赏。

UPDATE / FIX

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

javascript node.js reactjs openshift next.js
1个回答
2
投票

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)
© www.soinside.com 2019 - 2024. All rights reserved.