【问题标题】:.env variables in prod enviroment (dotenv-webpack)prod 环境中的 .env 变量(dotenv-webpack)
【发布时间】:2020-07-30 04:30:11
【问题描述】:

我的代码在开发模式下运行良好。但是当尝试在 prod 模式下使用它时,我收到一个错误,即由于未定义的变量(.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

}

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

提前致谢!

【问题讨论】:

    标签: javascript webpack dotenv


    【解决方案1】:

    我看到你正在使用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",
    

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 2017-05-30
      • 2021-11-08
      • 2021-11-05
      • 2021-11-19
      • 2017-10-08
      • 2021-10-14
      • 1970-01-01
      • 2020-12-29
      相关资源
      最近更新 更多