1. 代码分析


import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

async function loadConfig() {
    try {
      const response = await fetch('/config.json');
      if (!response.ok) {
        throw new Error('Failed to load configuration');
      }
      const config = await response.json();
      console.log(config)
      app.config.globalProperties.$config = config; // 将配置添加到全局属性
      console.log(app.config.globalProperties.$config)
    } catch (error) {
      console.error(error);
      app.config.globalProperties.$config = { apiUrl: 'http://127.0.0.1' }; // 默认值
    }
}
  
loadConfig().then(() => {
    app.mount('#app');
});

2. 实现原理

这段代码实现了一个运行时配置加载机制,主要特点是:

  • 应用启动前异步加载配置文件

  • 配置加载完成后再挂载应用

  • 提供了默认配置作为降级方案

3. 生产环境配置步骤

3.1 准备配置文件

// public/config.json
{
  "apiUrl": "http://api.example.com",
  "version": "1.0.0",
  "features": {
    "enableFeatureA": true,
    "enableFeatureB": false
  }
}

3.2 部署配置

  1. 将config.json放在项目的public目录下

  2. 构建时会自动复制到dist目录

  3. 部署时可以替换此文件实现配置更新

3.3 Nginx配置示例

server {
    listen 80;
    server_name example.com;

    location / {
        root /usr/share/nginx/html;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    # 确保config.json可访问
    location /config.json {
        root /usr/share/nginx/html;
        add_header Cache-Control no-cache;
    }
}

4. 使用注意事项

4.1 类型定义

// types/config.d.ts
interface Config {
    apiUrl: string;
    [key: string]: any;
}

declare module 'vue' {
    interface ComponentCustomProperties {
        $config: Config;
    }
}

4.2 在组件中使用

<script setup lang="ts">
import { getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()!
const apiUrl = proxy!.$config.apiUrl
</script>

4.3 配置文件更新

# 更新配置文件示例
cp new-config.json /usr/share/nginx/html/config.json

5. 优缺点分析

优点:

  1. 无需重新构建即可修改配置

  2. 适合容器化部署场景

  3. 便于运维人员管理

  4. 支持动态配置

缺点:

  1. 首次加载需要额外的网络请求

  2. 需要确保配置文件的安全性

  3. 异步加载可能导致短暂的加载状态

6. 安全建议

  1. 使用HTTPS传输配置文件

  2. 添加适当的访问控制

  3. 不要在配置文件中存储敏感信息

  4. 定期备份配置文件

  5. 配置文件的权限控制

7. 最佳实践

  1. 配置文件命名规范:

config.json          # 生产环境
config.dev.json      # 开发环境
config.test.json     # 测试环境
  1. 错误处理完善:

async function loadConfig() {
    try {
        const response = await fetch('/config.json');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const config = await response.json();
        // 配置验证
        if (!config.apiUrl) {
            throw new Error('Invalid configuration: apiUrl is required');
        }
        app.config.globalProperties.$config = config;
    } catch (error) {
        console.error('Failed to load configuration:', error);
        // 使用默认配置
        app.config.globalProperties.$config = {
            apiUrl: 'http://127.0.0.1',
            // 其他默认配置
        };
    }
}
  1. 配置文件结构建议:

{
    "apiUrl": "http://api.example.com",
    "version": "1.0.0",
    "features": {
        "feature1": true,
        "feature2": false
    },
    "settings": {
        "timeout": 5000,
        "retryCount": 3
    }
}

通过以上配置方案,可以实现生产环境的灵活配置管理,便于维护和更新。记住要根据实际需求调整配置文件的结构和内容,确保配置的安全性和可维护性。