prod 环境中的 .env 变量(dotenv-webpack)

.env variables in prod enviroment (dotenv-webpack)

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

我正在使用 webpack 和 dotenv-webpack 为产品打包文件。

控制台错误

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
}


.env

USERNAME = ******

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 你可以更好地划分你的配置 look here

webpack.config.js

module.exports = env => {
   console.log(env === "prod"? "production mode": "development mode")
    return require(`./webpack.${env}.js`);
};

然后我们在脚本中传递 --env,这样它将 运行 为 devprod:

选择的配置
  "dev": "webpack --env dev",
  "prod": "webpack --env prod",

这可能无法回答您的问题,但可以帮助您更好地拆分配置。

你可以通过在参数中传递 env 来为你的产品配置做同样的事情。

所以一般来说你可以传递任何参数:

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