TypeScript 表示 NextJS 的环境变量未定义。

10

我正在尝试使用'react-google-login'进行社交登录。

根目录下的.env文件

NEXT_PUBLIC_GOOGLE_CLIENT_ID=askfjaskf

Ready.tsx

import { GoogleLogin } from "react-google-login";
<GoogleLogin
    clientId={process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID}
    render={(props) => (
      <div onClick={props.onClick}>
        <div>구글 로그인</div>
      </div>
    )}
    onSuccess={(res) => {
      const { profileObj } = res as any;
      setStep(AuthStep.AGREE);
    }}
    onFailure={(res) => {
      console.log("Google Error", res);
    }}
  />

在clientId中,它说

没有重载与此调用匹配。 第1个重载('(props: GoogleLoginProps | Readonly): GoogleLogin')产生了以下错误。 类型“string | undefined”不能赋值给类型“string”。 类型“undefined”不能赋值给类型“string”。 第2个重载('(props: GoogleLoginProps, context: any): GoogleLogin')产生了以下错误。 类型“string | undefined”不能赋值给类型“string”。 类型“undefined”不能赋值给类型“string”。ts(2769) index.d.ts(80, 12):所期望的类型来自于在此处声明的“clientId”属性,其类型为“IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<...>”。

我不知道为什么它可以是undefined。 在本地可行但在生产环境部署时却不行。有人能帮忙吗?

3个回答

14
declare global { ...这个答案对我没有用。 但是下面这个可以:
declare namespace NodeJS {
  interface ProcessEnv {
    JWT_TOKEN: string;
  }
}

next-env.d.ts 文件中添加对新文件的引用:
/// <reference types="./environment" />
UPD 2022 (next.js 12+):

Next.js 文档中提到:

在你的项目根目录下会创建一个名为next-env.d.ts的文件[...]您不应该删除或编辑它,因为它可能随时更改。

相反,请使用推荐的方法:

不要编辑next-env.d.ts,您可以通过添加一个新的文件例如additional.d.ts并在tsconfig.json的include数组中引用它来包含其他类型。


1
这对我起作用了,但我不需要在 next-env.d.ts 中添加对新文件的引用。我将文件命名为 environmnt.d.td,vs code会自动识别它。 - chuckieDub
1
Next.js文档提到不要直接编辑next-env.d.ts文件。相反,应创建一个单独的filename.d.ts文件,然后将其添加到您的tsconfig.json文件中的include属性下 - Nextjs doc link - shaahiin
链接的Next.js文档中,我找不到关于环境变量的任何信息。可能他们已经进行了更改?还有其他地方可以找到相关文档吗? - undefined

9

我遇到了相同的问题,但是与不同的 ENV 变量有关。问题在于 TypeScript 不知道是否存在某个 ENV 变量。

请查看这个相关问题: 使用 TypeScript 中的 process.env

它帮助我解决了这个问题。只需要创建 environment.d.ts 并将全局 ENV 变量声明为你想要的类型即可。

declare global {
  namespace NodeJS {
    interface ProcessEnv {
      NEXT_PUBLIC_GOOGLE_CLIENT_ID: string; // this is the line you want
      NODE_ENV: 'development' | 'production';
      PORT?: string;
      PWD: string;
    }
  }
}

6

你需要将它转换为字符串

export default NextAuth({
providers: [
    GoogleProvider({
        clientId: process.env.GOOGLE_ID as string,
        clientSecret: process.env.GOOGLE_SECRET as string,
    }),
]})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接