nextjs env变量始终未定义 [英] Nextjs env variable is always undefined

查看:94
本文介绍了nextjs env变量始终未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目设置如下:

project-ci (only docker)
  nextjs
  backend

阶段和生产是相同的,所以我传入了仅对此参数进行阶段转换的 docker-compose.yml 文件(这两个环境都是首先使用这些命令构建的 npm run build 然后 npm run start )

Staging and Production are the same so I pass in docker-compose.yml file of staging only this argument (both environments are built with these commands first npm run build and then npm run start)

args:
    NEXT_PUBLIC_URL: arbitrary_value

在nextjs的 Dockerfile 中的

放置了这些命令

in Dockerfile of the nextjs put these commands

ARG NEXT_PUBLIC_URL
ENV NEXT_PUBLIC_URL=$NEXT_PUBLIC_URL

so变量然后将通过 process.env.NEXT_PUBLIC_URL 在nextjs中访问.到目前为止,如果我尝试在 index.js 中使用 console.log(process.env.NEXT_PUBLIC_URL),则该值始终是 undefined .任何想法出了什么问题,还检查了文档,但结果仍然是 undefined

so variable will then be accessible in nextjs with process.env.NEXT_PUBLIC_URL. So far if I try to console.log(process.env.NEXT_PUBLIC_URL) in index.js the value is always undefined. Any ideas what is wrong, also checked the docs but the result was still undefined

https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration

https://nextjs.org/docs/api-reference/next.config.js/environment-variables

推荐答案

我可以使用公共运行时配置属性访问环境变量:

I can access env variables using public runtime config property:

next.config.js

next.config.js

module.exports = {
    publicRuntimeConfig: {
      NEXT_PUBLIC_URL: process.env.NEXT_PUBLIC_URL,
    }
};

然后:

import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig.NEXT_PUBLIC_URL);

如果它不起作用,请确保在docker容器中创建了env变量

If it doesn't work, make sure the env variables are created in docker container

这篇关于nextjs env变量始终未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆