Typescript 说 NextJS 环境变量未定义

piz*_*ice 11 authentication typescript next.js react-google-login

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

\n

根目录中的.env

\n
NEXT_PUBLIC_GOOGLE_CLIENT_ID=askfjaskf\n
Run Code Online (Sandbox Code Playgroud)\n

就绪.tsx

\n
import { GoogleLogin } from "react-google-login";\n<GoogleLogin\n    clientId={process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID}\n    render={(props) => (\n      <div onClick={props.onClick}>\n        <div>\xea\xb5\xac\xea\xb8\x80 \xeb\xa1\x9c\xea\xb7\xb8\xec\x9d\xb8</div>\n      </div>\n    )}\n    onSuccess={(res) => {\n      const { profileObj } = res as any;\n      setStep(AuthStep.AGREE);\n    }}\n    onFailure={(res) => {\n      console.log("Google Error", res);\n    }}\n  />\n
Run Code Online (Sandbox Code Playgroud)\n

在 clientId 中,它说

\n
\n

没有与此调用匹配的重载。\n重载 1 of 2,“(props: GoogleLoginProps | Readonly): GoogleLogin”,出现以下错误。\n键入 'string | 无法将“未定义”分配给“字符串”类型。\n无法将“未定义”类型分配给“字符串”类型。\n重载 2 个,共 2 个“(props: GoogleLoginProps, context: any): GoogleLogin”,出现以下错误。 \n输入“字符串|” undefined' 不能分配给类型 'string'。\n类型 'undefined' 不能分配给类型 'string'.ts(2769)\nindex.d.ts(80, 12): 预期类型来自属性 'clientId'这是在类型“IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<...>”上声明的

\n
\n

我不知道为什么它说它可以是未定义的。\n它在本地工作,但在生产部署中不起作用。有人可以帮忙吗?

\n

mrk*_*ima 20

答案declare global { ...对我来说不起作用。

推荐的方法是创建类型声明文件,例如env.d.ts使用以下声明:

declare namespace NodeJS {
  interface ProcessEnv {
    JWT_TOKEN: string;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后将此引用添加到您的tsconfig.json文件中include

declare namespace NodeJS {
  interface ProcessEnv {
    JWT_TOKEN: string;
  }
}
Run Code Online (Sandbox Code Playgroud)

不鼓励的做法

不要在 中添加引用next-end.d.ts,Next.js文档提到

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

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

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


小智 9

我有同样的问题,但使用不同的 ENV 变量,问题是打字稿不知道 ENV 变量是否存在。

检查另一个问题: using process.env in TypeScript

它帮助我解决了这个问题。只需要创建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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

你需要将它转换为字符串

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