vue 設置項目全局配置文件,可靈活切換 本地/開發/測試/投產環境

vue-cli-plugin-app-config

介紹

一個vue項目配置文件管理的解決方案,可方便開發者在本地環境/測試環境/投產環境等多種配置裏面快速切換css

快速使用

添加插件
yarn add vue-cli-plugin-app-config

// 或者

npm i vue-cli-plugin-app-config --save-dev
應用插件到項目中
vue add vue-cli-plugin-app-config
配置插件 vue.config.js
{
   ...other config
   pluginOptions: {
      // options
      'app-config': {
        file: './app.config.js',
        default: 'dev'
      }
   }
}

插件配置項 options

配置項 默認值 描述
file ./app.config.js 配置文件路徑,默認爲項目根目錄,和 vue.config.js 同級
default dev 默認使用的配置環境

app.config.js 配置文件結構示例

module.exports = {
  // 不一樣環境環境配置
  env: {
    // 開發環境
    dev: {
      apihost: 'http://local.api.com'
    },
    // 測試環境
    test: {
      apihost: 'http://test.api.com'
    },
    // 投產環境
    prod: {
      apihost: 'http://bbs.api.com'
    },
    ...
  },
  // 公用配置
  common: {
    // 接口超時時間
    timeout: 5000,
    // 主題配置
    theme: 'red',
    ...
  }
}

使用不一樣的環境啓動項目(以yarn爲例)

開發環境
// 默認 dev環境,因此可加可不加
yarn serve --dev
測試環境
yarn serve --test
正式環境
yarn serve --prod
用戶自定義環境
yarn serve --xxx

使用不一樣的環境編譯項目(以yarn爲例)

開發環境
// 默認 dev環境,因此可加可不加
yarn build --dev
測試環境
yarn build --test
正式環境
yarn build --prod
用戶自定義環境
yarn build --xxx

項目中使用配置內容

使用本插件之後,會在項目全局生成一個 $config 對象,可在任意js文件中經過 $config 直接獲取配置內容html

上文中的配置文件,以dev環境啓動爲例,最終獲得的 $config 文件以下
// $config
{
  apihost: 'http://local.api.com',
  // 接口超時時間
  timeout: 5000,
  // 主題配置
  theme: 'red'
}
示例
<template lang="html">
  <div>
    apihost: {{config.apihost}}
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 注入到當前組件
      config: $config
    }
  },
  mounted() {
    console.log('全局項目配置', $config)
  }
}
</script>

<style lang="css" scoped>
</style>
相關文章
相關標籤/搜索