JSPM

dyh-weather-sdk

1.0.1
    • ESM via JSPM
    • ES Module Entrypoint
    • Export Map
    • Keywords
    • License
    • Repository URL
    • TypeScript Types
    • README
    • Created
    • Published
    • Downloads 5
    • Score
      100M100P100Q62847F
    • License MIT

    天气信息获取SDK,支持浏览器和Node.js环境

    Package Exports

    • dyh-weather-sdk
    • dyh-weather-sdk/browser
    • dyh-weather-sdk/node

    Readme

    Dyh Weather SDK

    一个支持浏览器和Node.js环境的天气信息获取SDK,使用原生JavaScript开发,支持TypeScript。

    特性

    • 🌐 多环境支持: 同时支持浏览器和Node.js环境
    • 🔐 身份认证: 内置认证机制,支持API密钥验证
    • 📦 条件导出: 一套代码,多端输出,自动适配运行环境
    • 🛡️ TypeScript: 完整的类型定义,提供更好的开发体验
    • 轻量级: 无外部依赖,使用原生JavaScript实现
    • 🔄 批量请求: 支持批量获取多个城市的天气信息
    • 🎨 DOM渲染: 内置美观的天气信息展示界面,支持自定义配置

    安装

    npm install dyh-weather-sdk

    快速开始

    浏览器环境

    <!DOCTYPE html>
    <html>
    <head>
        <title>天气SDK示例</title>
    </head>
    <body>
        <script src="node_modules/dyh-weather-sdk/dist/browser/index.js"></script>
        <script>
            const sdk = new DyhWeatherSDK.WeatherSDK({
                authUserAk: '123456'
            });
    
            sdk.getWeather('110100').then(weather => {
                console.log('天气信息:', weather);
            }).catch(error => {
                console.error('获取失败:', error.message);
            });
        </script>
    </body>
    </html>

    Node.js环境

    const { WeatherSDK } = require('dyh-weather-sdk');
    
    const sdk = new WeatherSDK({
        authUserAk: '123456'
    });
    
    async function getWeather() {
        try {
            const weather = await sdk.getWeather('110100');
            console.log('天气信息:', weather);
        } catch (error) {
            console.error('获取失败:', error.message);
        }
    }
    
    getWeather();

    ES模块

    import WeatherSDK from 'dyh-weather-sdk';
    
    const sdk = new WeatherSDK({
        authUserAk: '123456'
    });
    
    const weather = await sdk.getWeather('110100');
    console.log('天气信息:', weather);

    DOM渲染功能

    SDK内置了美观的天气信息展示界面,支持自动渲染到指定的DOM元素中。

    基础使用

    <!DOCTYPE html>
    <html>
    <head>
        <title>天气SDK DOM渲染示例</title>
    </head>
    <body>
        <!-- 天气信息将渲染到这个div中 -->
        <div id="weather-container"></div>
        
        <script src="node_modules/dyh-weather-sdk/dist/browser/index.js"></script>
        <script>
            const sdk = new DyhWeatherSDK.WeatherSDK({
                authUserAk: '123456',
                domId: 'weather-container'  // 指定DOM元素ID
            });
    
            // 获取天气信息,SDK会自动渲染到DOM中
            sdk.getWeather('110100');
        </script>
    </body>
    </html>

    自定义配置

    const sdk = new DyhWeatherSDK.WeatherSDK({
        authUserAk: '123456',
        domId: 'weather-container',
        domOptions: {
            showCurrent: true,        // 显示当前天气
            showForecast: true,       // 显示天气预报
            showLifeIndex: true,      // 显示生活指数
            showAlerts: true,         // 显示预警信息
            showHourly: false,        // 显示小时预报
            customClass: 'my-weather', // 自定义CSS类名
            useDefaultStyles: true    // 使用默认样式
        }
    });

    DOM渲染方法

    renderToDOM(weatherData: WeatherData): void

    手动渲染天气数据到DOM。

    const weather = await sdk.getWeather('110100');
    sdk.renderToDOM(weather); // 手动渲染

    clearDOM(): void

    清空DOM渲染内容。

    sdk.clearDOM(); // 清空天气显示

    updateDOMOptions(options: DOMRenderOptions): void

    更新DOM渲染选项。

    sdk.updateDOMOptions({
        showCurrent: false,
        showForecast: true,
        useDefaultStyles: false
    });

    isDOMRendererAvailable(): boolean

    检查DOM渲染器是否可用。

    if (sdk.isDOMRendererAvailable()) {
        console.log('DOM渲染器可用');
    }

    样式自定义

    SDK提供了完整的默认样式,你也可以通过CSS进行自定义:

    /* 自定义天气组件样式 */
    .weather-widget {
        border-radius: 20px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    }
    
    .weather-current {
        background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);
    }
    
    /* 更多自定义样式... */

    API文档

    WeatherSDK

    主要的SDK类,用于获取天气信息。

    构造函数

    new WeatherSDK(options: WeatherSDKOptions)

    参数:

    • options.authUserAk (string): 认证密钥,必需
    • options.baseURL (string): API基础URL,可选,默认为 https://yhhl.love
    • options.timeout (number): 请求超时时间(毫秒),可选,默认为 10000
    • options.domId (string): DOM元素ID,可选,用于自动渲染天气信息
    • options.domOptions (DOMRenderOptions): DOM渲染配置选项,可选

    方法

    getWeather(code: string): Promise

    获取指定城市的天气信息。

    参数:

    • code (string): 城市编码

    返回值:

    • Promise<WeatherInfo>: 天气信息对象

    示例:

    const weather = await sdk.getWeather('110100');
    console.log(weather.city); // 城市名称
    console.log(weather.temperature); // 温度
    console.log(weather.description); // 天气描述
    getWeatherBatch(codes: string[]): Promise<WeatherInfo[]>

    批量获取多个城市的天气信息。

    参数:

    • codes (string[]): 城市编码数组

    返回值:

    • Promise<WeatherInfo[]>: 天气信息对象数组

    示例:

    const weathers = await sdk.getWeatherBatch(['110100', '310100', '440100']);
    weathers.forEach(weather => {
        console.log(`${weather.city}: ${weather.temperature}°C`);
    });
    updateAuth(authUserAk: string): void

    更新认证密钥。

    updateBaseURL(baseURL: string): void

    更新API基础URL。

    updateTimeout(timeout: number): void

    更新请求超时时间。

    类型定义

    WeatherInfo

    天气信息接口。

    interface WeatherInfo {
        city: string;           // 城市名称
        code: string;           // 城市编码
        temperature: number;    // 温度
        description: string;    // 天气描述
        humidity?: number;      // 湿度(可选)
        windSpeed?: number;     // 风速(可选)
        updateTime: string;     // 更新时间
    }

    WeatherSDKError

    SDK错误类。

    class WeatherSDKError extends Error {
        constructor(message: string, code?: number, status?: number);
    }

    开发

    构建

    # 安装依赖
    npm install
    
    # 构建所有版本
    npm run build
    
    # 构建特定版本
    npm run build:node      # Node.js版本
    npm run build:browser   # 浏览器版本
    npm run build:esm       # ES模块版本
    npm run build:types     # TypeScript类型定义

    测试

    npm test

    开发模式

    npm run dev

    示例

    查看 examples/ 目录下的示例文件:

    • browser.html - 浏览器环境基础示例
    • dom-example.html - DOM渲染功能完整示例
    • node-commonjs.cjs - Node.js CommonJS示例
    • node-esm.mjs - Node.js ES模块示例
    • node-typescript.ts - Node.js TypeScript示例

    运行示例

    # 浏览器示例
    open examples/browser.html
    open examples/dom-example.html
    
    # Node.js示例
    node examples/node-commonjs.cjs
    node examples/node-esm.mjs
    npx ts-node examples/node-typescript.ts

    许可证

    MIT License

    贡献

    欢迎提交Issue和Pull Request!