繁体   English   中英

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

[英].env variables in prod enviroment (dotenv-webpack)

我的代码在开发模式下运行良好。 但是当尝试在 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 文件中的实际用户名。

获取城市数据.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 您可以更好地拆分配置看这里

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",

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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