一個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' } } }
配置項 | 默認值 | 描述 |
---|---|---|
file | ./app.config.js | 配置文件路徑,默認爲項目根目錄,和 vue.config.js 同級 |
default | dev | 默認使用的配置環境 |
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', ... } }
開發環境
// 默認 dev環境,因此可加可不加 yarn serve --dev
測試環境
yarn serve --test
正式環境
yarn serve --prod
用戶自定義環境
yarn serve --xxx
開發環境
// 默認 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>