vue-cli 佈署的環境參數
在 vue-cli 官方網站有提到可以依照 mode 來配置環境變數 Environment Variables ,這裡的重點如下:
Note that only
NODE_ENV
,BASE_URL
, and variables that start withVUE_APP_
will be statically embedded into the client bundle withwebpack.DefinePlugin
. It is to avoid accidentally exposing a private key on the machine that could have the same name.請注意,只有
NODE_ENV
,BASE_URL
和以VUE_APP_開頭
的變量將通過webpack.DefinePlugin
靜態嵌入到客戶端程式包中。 這是為了避免意外公開可能具有相同名稱的私鑰。
- 模式(mode)
模式是 Vue CLI 專案中一個重要的概念。預設情況下,一個 Vue CLI 專案有三個模式:
- development 模式用於 vue-cli-service serve
- production 模式用於 vue-cli-service build 和 vue-cli-service test:e2e
- test 模式用於 vue-cli-service test:unit
- 環境變數和模式 Environment Variables
你可以替換你的專案根目錄中的下列檔來指定環境變數:
.env # 在所有的環境中被載入 .env.local # 在所有的環境中被載入,但會被 git 忽略 .env.[mode] # 只在指定的模式中被載入 .env.[mode].local # 只在指定的模式中被載入,但會被 git 忽略
- 實作
瞭解概念後,首先建立三個環境變數檔案 .env.apache
、.env.development
、.env.production
,以 .env.apache
/** 在 npm run build 可以使用的參數 */ PUBLIC_PATH = "/vue2Apps/" OUTPUT_DIR = "W:/xampp/htdocs/vue2Apps/" /** * 只有以 VUE_APP_ 開頭的變數會被 webpack.DefinePlugin 靜態嵌入到用戶端側的包中。 * 可以在應用的代碼中訪問: console.log(process.env.VUE_APP_HOME_URL) */ VUE_APP_HOME_URL = "http://localhost:8090/vue2Apps/" VUE_APP_AXIOS_BASE_URL = "https://dev-labs.com"
修改 package.json 裡的 script 區段,增加 serve:apache
& build:apache
,主要是加入 --mode apache
的參數
"scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "serve:apache": "vue-cli-service serve --mode apache", "build:apache": "vue-cli-service build --mode apache", "test:unit": "vue-cli-service test:unit", "lint": "vue-cli-service lint", "i18n:report": "vue-cli-service i18n:report --src './src/**/*.?(js|vue)' --locales './src/locales/**/*.json'" }
執行 npm run build:apache
時,就會依照參數檔 .env.apache
來作相對應的替換了
你必須 登入 才能發表評論。