Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 产品环境中的.env变量(dotenv网页包)_Javascript_Webpack_Dotenv - Fatal编程技术网

Javascript 产品环境中的.env变量(dotenv网页包)

Javascript 产品环境中的.env变量(dotenv网页包),javascript,webpack,dotenv,Javascript,Webpack,Dotenv,我的代码在开发模式下工作得非常好。但是当尝试在prod模式下使用它时,我得到一个错误,即由于未定义的变量(在.env中的变量)而无法到达API请求 我正在使用webpack和dotenv webpack为prod绑定文件 控制台错误 main.js?__WB_REVISION__=b1e064aa60232b9e77ec8ee2ca52e4f8:1 GET http://api.geonames.org/searchJSON?q=quito&username=undefined 401

我的代码在开发模式下工作得非常好。但是当尝试在prod模式下使用它时,我得到一个错误,即由于未定义的变量(在.env中的变量)而无法到达API请求

我正在使用webpack和dotenv webpack为prod绑定文件

控制台错误

main.js?__WB_REVISION__=b1e064aa60232b9e77ec8ee2ca52e4f8:1
GET http://api.geonames.org/searchJSON?q=quito&username=undefined 401 (Unauthorized)
如您所见,用户名显示为未定义,而不是.env文件中的实际用户名

getCityData.js

import axios from 'axios';

   // http://api.geonames.org/searchJSON?q=miami&username=username

 async function getCityData(username, city) {
    const url=  "http://api.geonames.org/searchJSON?q=",
    completeURL = `${url}${city}&username=${username}`
    const data = {};

    try {
        await axios.get(completeURL).then((response) => {
            data.lng = response.data.geonames[0].lng
            data.lat = response.data.geonames[0].lat
            data.country = response.data.geonames[0].countryName
            // console.log(response.data.geonames[0])
          });
          // console.log(data)
          return data;
    }
    catch(error) {
        console.log("This error", error);
      }
}

export   {
    getCityData
}


环境署署长

getTravelData.js

import { getCityData } from "./getCityData"
import { getWeatherData } from "./getWeatherData"
import { getPicture } from "./getPicture";
import { updateUI } from "./updateUI";

   async function getTavel (where) {
    const username = process.env.USERNAME;
    const weatherbitKey = process.env.weatherbit_key;
    const key = process.env.pixabay_key;
    await getCityData(username, where).then((data) =>{ 

        getWeatherData(data.lng, data.lat, weatherbitKey, data.country).then((weatherData) => {
            return weatherData

        }).then((data) => {
            getPicture(where, key, data).then( (data) => {
                updateUI(data)
            }) 
        })

    })


webpack.prod.js

const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const workboxPlugin = require('workbox-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const Dotenv = require('dotenv-webpack');



module.exports = {
    entry: './src/client/index.js',
    optimization: {
        minimizer: [new TerserPlugin({}), new OptimizeCSSAssetsPlugin({})],
    },
    output: {
        libraryTarget: 'var',
        library: 'Client'
    },
    mode: 'production',
    module: {
        rules: [
            {
                test: '/\.js$/',
                exclude: /node_modules/,
                loader: 'babel-loader'
            },
            {
                test:/\.scss$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: ['file-loader'],
              },
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/client/views/index.html',
            filename: './index.html'
        }),
        new workboxPlugin.GenerateSW(),
        new MiniCssExtractPlugin({filename: '[name].css'}),
        new Dotenv({
            path: path.resolve(__dirname, './.env'),
            safe: false,
            systemvars: true
        })
    ]}
index.js

import "./styles/styles.scss";
import { addHandleSubmit } from "./js/HandleSubmit";
import { getCityData } from "./js/getCityData";
import { getWeatherData } from "./js/getWeatherData";
import { handleDates} from "./js/handleDates"

document.getElementById("add-trip").addEventListener('click', addHandleSubmit)

export {
    addHandleSubmit,
    getCityData,
    getWeatherData,
    handleDates

}

为什么在生产模式下用户名变量导致未定义


提前谢谢

我看到您使用的是
Dotenv
,这还不错,但使用webpack,您可以在配置之间进行更好的拆分

webpack.config.js

module.exports = env => {
   console.log(env === "prod"? "production mode": "development mode")
    return require(`./webpack.${env}.js`);
};
然后我们在脚本中传递
--env
,这样它将运行为
dev
prod
选择的配置:

  "dev": "webpack --env dev",
  "prod": "webpack --env prod",
这可能无法回答您的问题,但它将帮助您更好地进行配置拆分

通过在参数中传递
env
,您可以对prod配置执行相同的操作

因此,一般来说,您可以传递任何参数:

 "example": "webpack --env dev --foo hello",
 "example": "webpack --env dev --foo hello",