npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

env-manager-js

v1.2.1

Published

A flexible environment management tool for frontend applications with dynamic API switching

Readme

env-manager-js

🌍 一个灵活的前端环境管理工具,支持动态API切换和URL参数控制。

npm version License: MIT

✨ 特性

  • 🚀 动态环境切换 - 通过URL参数实时切换API环境,无需重新打包
  • 🔗 URL参数控制 - 通过URL参数实现透明的环境切换,便于调试和分享
  • 🔄 自动URL同步 - 自动将当前环境同步到URL参数,保持状态一致性
  • SSR兼容 - 完美支持服务端渲染环境
  • 🎯 TypeScript支持 - 完整的类型定义,提供最佳开发体验
  • 零依赖 - 轻量级实现,无外部依赖
  • 🔧 简洁配置 - 简化的配置选项,易于使用和维护

📦 安装

npm install env-manager-js
yarn add env-manager-js
pnpm add env-manager-js

🚀 快速开始

JavaScript 使用

import createEnvManager from 'env-manager-js';

// 创建环境管理器
const envManager = createEnvManager({
  envConfig: {
    dev: { baseURL: "//localhost:3000" },
    prod: { baseURL: "//api.example.com" }
  }
});

// 获取当前环境配置
const config = envManager.getConfig();
console.log('当前API地址:', config.baseURL);

TypeScript 使用

import createEnvManager, { 
  EnvManagerConfig, 
  EnvManager 
} from 'env-manager-js';

const config: EnvManagerConfig = {
  envConfig: {
    dev: { baseURL: "//localhost:3000", timeout: 10000 },
    test: { baseURL: "//test-api.example.com", timeout: 8000 },
    prod: { baseURL: "//api.example.com", timeout: 5000 }
  },
  paramName: 'apiSwitch',
  defaultEnv: 'dev'
};

const envManager: EnvManager = createEnvManager(config);

📖 API 文档

createEnvManager(config)

创建环境管理器实例。

参数

| 参数 | 类型 | 默认值 | 描述 | |------|------|--------|------| | envConfig | Object | {} | 环境配置映射对象 | | paramName | string | 'apiSwitch' | URL参数名 | | defaultEnv | string | 'pre' | 默认环境 | | enableLog | boolean | true | 是否启用控制台日志 |

返回值

返回环境管理器对象,包含以下方法:

| 方法 | 返回值 | 描述 | |------|--------|------| | getCurrentEnv() | string | 获取当前环境名称 | | getConfig(key?) | any | 获取当前环境的配置,可指定配置项 | | switchEnv(env) | boolean | 手动切换环境 | | getAvailableEnvs() | string[] | 获取所有可用环境 |

🎯 使用场景

1. React 项目集成

import React, { useState, useEffect } from 'react';
import createEnvManager from 'env-manager-js';
import axios from 'axios';

const envManager = createEnvManager({
  envConfig: {
    dev: { baseURL: "//localhost:3000", timeout: 10000 },
    test: { baseURL: "//test-api.example.com", timeout: 8000 },
    prod: { baseURL: "//api.example.com", timeout: 5000 }
  }
});

// 获取当前环境配置
const config = envManager.getConfig();
console.log('当前API地址:', config.baseURL);

// 创建axios实例
const apiClient = axios.create({
  baseURL: config.baseURL,
  timeout: config.timeout
});

function App() {
  const [currentEnv, setCurrentEnv] = useState('');
  
  useEffect(() => {
    setCurrentEnv(envManager.getCurrentEnv());
  }, []);
  
  const handleSwitchEnv = (env) => {
    envManager.switchEnv(env);
    setCurrentEnv(env);
    // 重新创建axios实例或刷新页面
    window.location.reload();
  };
  
  return (
    <div>
      <p>当前环境: {currentEnv}</p>
      {envManager.getAvailableEnvs().map(env => (
        <button key={env} onClick={() => handleSwitchEnv(env)}>
          切换到{env}环境
        </button>
      ))}
    </div>
  );
}

2. Vue 项目集成

// api/config.js
import createEnvManager from 'env-manager-js';

export const envManager = createEnvManager({
  envConfig: {
    dev: { baseURL: "//localhost:8080", timeout: 10000 },
    test: { baseURL: "//test-api.example.com", timeout: 8000 },
    prod: { baseURL: "//api.example.com", timeout: 5000 }
  }
});

export const config = envManager.getConfig();
// api/request.js
import axios from 'axios';
import { config } from './config.js';

const request = axios.create({
  baseURL: config.url,
  timeout: 10000
});

export default request;

3. 多项目配置

// 项目A的环境管理
const projectAEnvManager = createEnvManager({
  envConfig: {
    local: { baseURL: "//localhost:8080", timeout: 10000 },
    staging: { baseURL: "//staging-a.company.com", timeout: 8000 },
    production: { baseURL: "//api-a.company.com", timeout: 5000 }
  },
  paramName: 'apiEnv',
  defaultEnv: 'local'
});

// 获取项目A的配置
const configA = projectAEnvManager.getConfig();
console.log('项目A API地址:', configA.baseURL);

// 项目B的环境管理
const projectBEnvManager = createEnvManager({
  envConfig: {
    local: { baseURL: "//localhost:9000", timeout: 10000 },
    staging: { baseURL: "//staging-b.company.com", timeout: 8000 },
    production: { baseURL: "//api-b.company.com", timeout: 5000 }
  },
  paramName: 'bEnv',
  defaultEnv: 'local'
});

// 获取项目B的配置
const configB = projectBEnvManager.getConfig();
console.log('项目B API地址:', configB.baseURL);

🔄 环境切换逻辑

简化的纯URL参数方案

  1. 检查URL参数 - 如果URL中存在环境参数且有效,则使用该环境
  2. 默认环境兜底 - 如果没有URL参数或参数无效,则使用默认环境

切换方式

通过URL参数切换

# 开发环境
localhost:3000?apiSwitch=dev

# 测试环境
localhost:3000?apiSwitch=test

# 预发布环境
localhost:3000?apiSwitch=staging

# 生产环境
www.example.com?apiSwitch=prod

通过代码切换

// 手动切换到测试环境
envManager.switchEnv('test');

🛡️ 安全特性

  • 环境验证 - 只允许切换到配置中存在的环境
  • SSR兼容 - 在服务端渲染环境中安全降级
  • URL参数控制 - 通过URL参数实现透明的环境切换,便于调试和分享

🔧 高级配置

自定义日志

const envManager = createEnvManager({
  envConfig: {
    dev: { baseURL: "//localhost:3000" },
    prod: { baseURL: "//api.example.com" }
  },
  enableLog: false, // 关闭默认日志
});

// 自定义日志处理
const originalGetConfig = envManager.getConfig;
envManager.getConfig = function(key) {
  const config = originalGetConfig.call(this, key);
  console.log(`🔧 自定义日志: 获取配置`, key ? `${key}: ${config}` : config);
  return config;
};

环境切换回调

const envManager = createEnvManager({
  envConfig: {
    dev: { baseURL: "//localhost:3000" },
    prod: { baseURL: "//api.example.com" }
  }
});

// 监听环境切换
const originalSwitchEnv = envManager.switchEnv;
envManager.switchEnv = function(env) {
  const success = originalSwitchEnv.call(this, env);
  if (success) {
    console.log(`环境已切换到: ${env}`);
    // 执行自定义逻辑,如重新加载数据
    window.dispatchEvent(new CustomEvent('envChanged', { detail: env }));
  }
  return success;
};

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📄 许可证

MIT © woyangv

🔗 相关链接