简体   繁体   中英

.env variables in prod enviroment (dotenv-webpack)

My code works perfectly fine in development mode. But when attempting to use it in prod mode I get an error that the API request can't be reached due to undefined variables (variables in the.env).

I am using webpack and dotenv-webpack to bundle files for prod.

console error

main.js?__WB_REVISION__=b1e064aa60232b9e77ec8ee2ca52e4f8:1
GET http://api.geonames.org/searchJSON?q=quito&username=undefined 401 (Unauthorized)

as you can see the username appears as undefined rather than the actual one from the.env file.

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

}

why is the username variable resulting in undefined while in production mode?

Thanks in advance!

I see that you are using Dotenv which is not bad but with webpack you can have a better splitting between your configurations look here

webpack.config.js

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

Then we pass --env in the script so it will run the chosen configuration for dev or prod :

  "dev": "webpack --env dev",
  "prod": "webpack --env prod",

this may not answer your question but it will helps you for a better configuration splitting.

and you can do the same thing for your prod configuration by passing the env in the arguments.

so in general you can pass any argument:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM