Vue App环境变量可以在开发模式下读取,而不能在生产模式下读取

问题描述 投票:1回答:1

我正在使用Vue cli创建一个以Firebase为后端的vue应用。

我的应用程序中的文件通过引用.env文件中定义的环境变量来初始化Firebase数据库。

.env

FIREBASE_API_KEY=#################################
FIREBASE_AUTH_DOMAIN=#################################
FIREBASE_DB_URL=https://#################################
FIREBASE_PROJECT_ID=#################################
FIREBASE_STORAGE_BUCKET=#################################
FIREBASE_MESSAGING_SENDER_ID=#################################
AUTH_API=https://#################################

[.env.development.local.env.production.local包含相同的数据。

在我的应用程序中,我有一个看起来像这样的文件:

credentials.js

导出默认值{

config: {
apiKey: process.env.VUE_APP_FIREBASE_API_KEY,
authDomain: process.env.VUE_APP_FIREBASE_AUTH_DOMAIN,
storageBucket: process.env.VUE_APP_FIREBASE_STORAGE_BUCKET,
databaseURL: process.env.VUE_APP_FIREBASE_DB_URL,
projectId: process.env.VUE_APP_FIREBASE_PROJECT_ID,
messagingSenderId: process.env.VUE_APP_FIREBASE_MESSAGING_SENDER_ID
}

}

[当我使用yarn serve提供此应用的开发版本时,将初始化数据库,因此显然可以毫无问题地读取.env变量。但是,当我使用yarn build然后在dist中提供结果文件时,在控制台上出现错误:

 @firebase/database: FIREBASE FATAL ERROR: Can't determine Firebase Database URL.  Be sure to include databaseURL option when calling firebase.initializeApp().  

基本上是告诉我在生产模式下没有读取环境变量。

这是我的package.json:

{
  "name": "web-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@firebase/firestore": "^1.9.3",
    "axios": "^0.19.0",
    "core-js": "^3.3.2",
    "element-ui": "^2.12.0",
    "feather-icons": "^4.24.1",
    "firebase": "^7.2.3",
    "firebase-admin": "^8.9.2",
    "firebase-functions": "^3.3.0",
    "localforage": "^1.7.3",
    "node-ipc": "^9.1.1",
    "vue": "^2.6.10",
    "vue-feather": "^1.0.0",
    "vue-feather-icons": "^5.0.0",
    "vue-router": "^3.1.3",
    "vue2-animate": "^2.1.3",
    "vuedraggable": "^2.23.2",
    "vuefire": "^2.2.0",
    "vuex": "^3.1.1",
    "vuex-persist": "^2.1.1"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.0.0",
    "@vue/cli-service": "^4.0.0",
    "babel-eslint": "^10.0.3",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "vue-template-compiler": "^2.6.10"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "rules": {},
    "parserOptions": {
      "parser": "babel-eslint"
    }
  },
  "postcss": {
    "plugins": {
      "autoprefixer": {}
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]
}

谁能告诉我是什么原因造成的?

firebase vue.js environment-variables vue-cli dev-to-production
1个回答
0
投票

您需要在VUE_APP_文件中为变量加上.env前缀。

来自https://cli.vuejs.org/guide/mode-and-env.html#environment-variables

请注意,只有以VUE_APP_开头的变量将通过webpack.DefinePlugin静态地嵌入到客户端包中。

© www.soinside.com 2019 - 2024. All rights reserved.