在工程根目錄下創建 .env.development .env.production .env.staging 三個文件

.env.development本地開發環境文件中配置
# just a flag ENV = 'development' # base api VUE_APP_API_URL = / # vue-cli uses the VUE_CLI_BABEL_TRANSPILE_MODULES environment variable, # to control whether the babel-plugin-dynamic-import-node plugin is enabled. # It only does one thing by converting all import() to require(). # This configuration can significantly increase the speed of hot updates, # when you have a large number of pages. # Detail: https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/babel-preset-app/index.js VUE_CLI_BABEL_TRANSPILE_MODULES = true
這里的base api 可以代替線上環境地址,也可以代替測試環境地址,看自己替換的地址
.env.production 線上環境配置
# just a flag ENV = 'production' # base api VUE_APP_API_URL = /
.env.staging 測試環境配置
NODE_ENV = production # just a flag ENV = 'staging' # base api VUE_APP_API_URL = /
然后在package.json文件中配置

"build:prod": "vue-cli-service build", "build:stage": "vue-cli-service build --mode staging",
本地啟動 npm run dev
生產環境 npm run build:prod
測試環境 npm run build:stage
配置完之后,要在你的ajax請求的時候配置baseUrl;
我用的是axios,所以在配置請求地址的時候把配置文件的地址加上

