首页 > 解决方案 > vue 环境变量返回空对象

问题描述

我是 vue 和 webpack 的新手,当我在 vue 应用程序中使用 console.log(process.env.VUE_APP_API_URL) 时,会返回一个空对象。我有一个 .env.development 文件,其中包含:

VUE_APP_API_URL=http://localhost:8000/api

应用程序后端内置在 laravel 中,运行良好。但我希望能够将 api url 存储为环境变量。

我的 webpack.config.js

     var path = require('path')
     var webpack = require('webpack')
     module.exports = {
     entry: './src/main.js',
     output: {
     path: path.resolve(__dirname, './dist'),
     publicPath: '/dist/',
     filename: 'build.js'
     },
     module: {
     rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },
      {
        test: /\.scss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader'
        ],
      },
      {
        test: /\.sass$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader?indentedSyntax'
        ],
      },

      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            'scss': [
              'vue-style-loader',
              'css-loader',
              'sass-loader'
            ],
            'sass': [
              'vue-style-loader',
              'css-loader',
              'sass-loader?indentedSyntax'
            ]
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
    },
    resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
    },
    devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
    },
    performance: {
    hints: false
    },
    devtool: '#eval-source-map'
     }

    if (process.env.NODE_ENV === 'production') {
    module.exports.devtool = '#source-map'
    module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      },
    }),
     new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
     new webpack.LoaderOptionsPlugin({
      minimize: true
    }),
    ])
    }

我尝试运行 npm install dotenv-webpack --save-dev 并将其添加到 webpack 插件,但它仍然没有解决问题。我该如何解决这个问题?

标签: vue.jswebpack

解决方案


为了从 .env 文件加载配置,您需要先安装 dotenv 依赖项,并require("dotenv").config()在调用变量之前调用。这将加载变量并使用process.env.YOUR_VARIABLES


推荐阅读