NEXT JS 环境变量在我的本地系统中不起作用

分享于2022年07月17日 environment-variables next.js node.js reactjs 问答
【问题标题】:NEXT JS 环境变量在我的本地系统中不起作用(NEXT JS environment variables not working in my local system)
【发布时间】:2022-01-26 05:21:00
【问题描述】:

我对 Next.js 比较陌生,由于某种原因,在我的本地系统中我无法访问环境变量。我在这里提供所有相关文件。

pages/index.js

import type {NextPage} from 'next'
import {useEffect} from "react";

const Home: NextPage = (props) => {

    useEffect(()=>{
        console.log("From Client API_URL:", process.env.API_URL)
        console.log("From Client NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL)
    }, []);

    return (
        <>
            Hello World!
        
    )
}

export async function getServerSideProps() {
    console.log("From Client API_URL:", process.env.API_URL)
    console.log("From Client NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL)
    return {
        props: {
            hello: "World!"
        }
    }
}

export default Home

.env.local 文件

API_URL:https://fakestoreapi.com/
NEXT_PUBLIC_API_URL:https://fakestoreapi.com/

在浏览器中,我在控制台中得到了这个。

NEXT JS environment variables not working in my local system

在服务器中,我得到了这个

> npm run dev

> dev
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Loaded env from C:\...\next-app\.env.local
warn  - SWC minify beta enabled. https://nextjs.org/docs/messages/swc-minify-enabled
event - compiled client and server successfully in 361 ms (217 modules)
wait  - compiling / (client and server)...
event - compiled client and server successfully in 92 ms (220 modules)
From server API_URL: undefined
From server NEXT_PUBLIC_API_URL: undefined
wait  - compiling /_error (client and server)...
event - compiled client and server successfully in 78 ms (221 modules)

下一个js版本:12.0.7

节点js版本:14.17.1

npm 版本:8.1.4

  • 您打错了,您需要使用 = 为您的 .env 文件中的环境变量赋值,即 API_URL=https://fakestoreapi.com/

【解决方案1】:

您的 .env.local 似乎配置不正确, 您应该在使用 = not 为键赋值时:

.env.local

API_URL=https://fakestoreapi.com/
NEXT_PUBLIC_API_URL=https://fakestoreapi.com/