dotenv 未正确加载

dotenv is not loading properly

我在使用 dotenv 模块时遇到了一些问题。在我的项目中,我正在使用需要 API 密钥的 API。因此,在利用时: require('dotenv').config() 在我的文件顶部并请求 const API_KEY = process.env.API_KEY 从我的 .env 文件中获取值,当我 console.log 我的环境变量时,我不断得到一个“未定义”值。到目前为止,这是我的线索:

这里的参考是我试图引用 .env 变量的代码:

overview.js

import React from 'react';
import './overview.css';
import { RecentSearches } from '../Recent Searches/recentSearches';
import { Hourly } from '../Hourly/hourly';
import { Fiveday } from '../5 Day Forecast/fiveday';

require('dotenv').config();
console.log(require('dotenv').config());

export function Overview() {

    // this callback function receives the searched city entered from recentSearches and applies it to fetchForecast
    const getSearch = async (searchedCity) => {
        fetchForecast(searchedCity);
    }; 

    const fetchForecast = async (city) => {
        const api_key = process.env.API_KEY;
        console.log(api_key);
        // const api_key = '2220f5a5d83243938f764759211310';
        var BASE_URL = `http://api.weatherapi.com/v1/forecast.json?key=${api_key}&q=${city}&days=3&aqi=no&alerts=no`;
    
        const response = await fetch(BASE_URL);
        const data = await response.json();
        console.log(data);

        // collects all of the current weather info for your search
        const currentTempInfo = {
            city: data.location.name, 
            state: data.location.region, 
            epochDate: data.location.localtime_epoch, 
            message: data.current.condition.text, 
            wicon: data.current.condition.icon, 
            currentTemp: data.current.temp_f,
            currentHighTemp: data.forecast.forecastday[0].day.maxtemp_f,
            currentLowTemp: data.forecast.forecastday[0].day.mintemp_f,
            feelsLike: data.current.feelslike_f,
            humidity: data.current.humidity,
            rainLevel: data.current.precip_in,
            // hourlyTemps is an array, starts from midnight(index 0) and goes every hour until 11 pm(index 23)
            hourlyTemps: data.forecast.forecastday[0].hour.map((entry) => {
                let epochTime, temp;
                [epochTime, temp] = [entry.time_epoch, entry.temp_f];
                return [epochTime, temp];
            })
        };

        // console.log(currentTempInfo);
    
        const daycardInfo = [];
        // this for loop triggers and creates an array with all necessary values for the 
        function daycardForLoop() {
            for (let x=0; x < 3; x++) {
                const fcDayDates = data.forecast.forecastday[x].date_epoch;
                const dayInfo = data.forecast.forecastday[x].day; 
                const dayValues = {
                    dates: fcDayDates, 
                    message: dayInfo.condition.text, 
                    wicon: dayInfo.condition.icon, 
                    maxTemp: dayInfo.maxtemp_f, 
                    minTemp: dayInfo.mintemp_f, 
                    avgTemp: dayInfo.avgtemp_f
                };
                // pushes dayValues object into daycardInfor array
                daycardInfo.push(dayValues);
            };
        }; 
        
        daycardForLoop();
    
        // this updates the state with the forecast for the city entered
        const newData = {
            currentTempInfo: currentTempInfo,
            daycardInfo: daycardInfo
        };

        // this spits out the newly created forecast object
        return newData;
    };

    return (
        <div>
            <div className='jumbotron' id='heading-title'>
                <h1>Welcome to <strong>Weathered</strong>!</h1>
                <h3>A Simple Weather Dashboard </h3>
            </div>

            <div className='container-fluid' id='homepage-skeleton'>
                <div className='d-flex' id='center-page'>
                    <RecentSearches getSearch={getSearch}/>
        
                    <Hourly />
                </div>
            </div>

            <Fiveday />        
        </div>
    )
};


您必须在 webpack 配置中导入 dotenv,然后使用 DefinePlugin 将变量传递给您的 React 应用程序。

const webpack = require('webpack');
const dotenv = require('dotenv');

module.exports = () => {
  // Here you need to call config method of dotenv package 
  const env = dotenv.config().parsed;


  return {
    plugins: [
     new DefinePlugin({
        'process.env': JSON.stringify(env)
     })      
    ]
};

如果您使用的是 create-react-app (CRA),则不需要 dotenv。

create-react-app 有一个很好的 guide 解释了使用环境变量的多种方式(一种选择是使用根目录中的 .env 文件)。变量必须以 REACT_APP_.

开头

警告:不要使用任何机密作为环境变量(如 API 密钥)构建项目,您也会在指南中看到此警告。他们将暴露给任何访问您的 React 应用程序的人。

@aLittleSalty 对您的案例有正确的答案。您看到的错误是因为 dotenv 应该在节点 server/backend 中使用,而浏览器无权访问文件系统。

但是,如果您将节点用于 server/backend 并且偶然发现了这个问题,那么我的回答适用于您。

.env 文件路径默认为 path.resolve(process.cwd(), '.env')cwd 是当前工作目录:这意味着 dotenv 在代码为 运行.

的目录中查找文件

如果你想指定相对路径,这是你应该使用的:

const path = require('path');
console.log(require('dotenv').config({path: path.resolve(__dirname, '../../.env')}));

dotenv 文档:https://www.npmjs.com/package/dotenv#user-content-path