# @grafana/grafana-foundation-sdk 中文文档

规范地址：https://npmcn.com/package/%40grafana/grafana-foundation-sdk/

版本：0\.0\.22
npm 元数据更新时间：2026-10-29T15:04:36.310Z
中文译文更新时间：2026-11-16T21:42:32.990Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40grafana/grafana-foundation-sdk
原文对照：https://npmcn.com/package/%40grafana/grafana-foundation-sdk/?lang=original
项目主页：https://github.com/grafana/grafana-foundation-sdk
源码仓库：https://github.com/grafana/grafana-foundation-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：6.1 MB，1857 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2023-12-08T14:07:23.379Z
- 最新版本发布：2026-10-29T15:04:35.043Z
- 近 30 天下载量：791005（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：432（近 12 个月 31 个）

## 中文简介

一套用于构建和操纵Grafana对象的工具,类型和库.

## 安装

```sh
npm install @grafana/grafana-foundation-sdk
```

也可以使用：`pnpm add @grafana/grafana-foundation-sdk`、`yarn add @grafana/grafana-foundation-sdk`、`bun add @grafana/grafana-foundation-sdk`

## README

# Grafana 基金会 SDK – TypeScript

一套工具、类型和 _建设图书馆_ 用于在 TypeScript 中构建和操纵 Grafana 对象.

## 安装

```shell
yarn add '@grafana/grafana-foundation-sdk@~v0.0.22'
```

## 示例用途

[更多实例](https://github.com/grafana/grafana-foundation-sdk/tree/main/examples/typescript) 可在寄存器根处找到.

### 建造仪表板

```typescript
import { DashboardBuilder, RowBuilder } from '@grafana/grafana-foundation-sdk/dashboard';
import { DataqueryBuilder } from '@grafana/grafana-foundation-sdk/prometheus';
import { PanelBuilder } from '@grafana/grafana-foundation-sdk/timeseries';

const builder = new DashboardBuilder('[TEST] Node Exporter / Raspberry')
  .uid('test-dashboard-raspberry')
  .tags(['generated', 'raspberrypi-node-integration'])

  .refresh('1m')
  .time({from: 'now-30m', to: 'now'})
  .timezone('browser')

  .withRow(new RowBuilder('Overview'))
  .withPanel(
    new PanelBuilder()
      .title('Network Received')
      .unit('bps')
      .min(0)
      .withTarget(
        new DataqueryBuilder()
          .expr('rate(node_network_receive_bytes_total{job="integrations/raspberrypi-node", device!="lo"}[$__rate_interval]) * 8')
          .legendFormat("{{ device }}")
      )
  )
;

console.log(JSON.stringify(builder.build(), null, 2));
```

### 定义自定义查询类型

支持所有核心数据源及其查询类型的SDK飞船, 它可以为私人/第三方插件扩展.

要做到这一点,请为自定义查询定义一个类型和一个构建器:

```typescript
// customQuery.ts
import { Builder, Dataquery } from '@grafana/grafana-foundation-sdk/cog';

export interface CustomQuery {
    // refId and hide are expected on all queries
    refId?: string;
    hide?: boolean;


    // query is specific to the CustomQuery type
    query: string;

    // Let cog know that CustomQuery is a Dataquery variant
    _implementsDataqueryVariant(): void;
}

export const defaultCustomQuery = (): CustomQuery => ({
    query: "",
    _implementsDataqueryVariant() {},
});

export class CustomQueryBuilder implements Builder<Dataquery> {
    private readonly internal: CustomQuery;

    constructor(query: string) {
        this.internal = defaultCustomQuery();
        this.internal.query = query;
    }

    build(): CustomQuery {
        return this.internal;
    }

    refId(refId: string): this {
        this.internal.refId = refId;
        return this;
    }

    hide(hide: boolean): this {
        this.internal.hide = hide;
        return this;
    }
}
```

自定义查询类型现在可以照常用于构建一个仪表板:

```typescript
import { DashboardBuilder, RowBuilder } from '@grafana/grafana-foundation-sdk/dashboard';
import { PanelBuilder as TimeSeriesBuilder } from "@grafana/grafana-foundation-sdk/timeseries";
import { CustomQueryBuilder } from "./customQuery";

const builder = new DashboardBuilder('Custom query type')
    .uid('test-custom-query-type')

    .refresh('1m')
    .time({ from: 'now-30m', to: 'now' })

    .withRow(new RowBuilder('Overview'))
    .withPanel(
        new TimeSeriesBuilder()
            .title('Sample panel')
            .withTarget(
                new CustomQueryBuilder("query here")
            )
    );

console.log(JSON.stringify(builder.build(), null, 2));
```

### 定义自定义面板类型

支援所有核心板的SDK飞船可以扩展至 私人/第三方插件.

为此,定义自定义面板选项的类型和构建器:

```typescript
// customPanel.ts
import * as dashboard from '@grafana/grafana-foundation-sdk/dashboard';

export interface CustomPanelOptions {
    makeBeautiful?: boolean;
}

export const defaultCustomPanelOptions = (): CustomPanelOptions => ({
});

export class CustomPanelBuilder extends dashboard.PanelBuilder {
    constructor() {
        super();
        this.internal.type = "custom-panel"; // panel plugin ID
    }

    makeBeautiful(): this {
        if (!this.internal.options) {
            this.internal.options = defaultCustomPanelOptions();
        }
        this.internal.options.makeBeautiful = true;
        return this;
    }
}
```

现在可以像往常一样使用自定义面板类型来构建一个仪表板:

```typescript
import { DashboardBuilder, RowBuilder } from '@grafana/grafana-foundation-sdk/dashboard';
import { CustomPanelBuilder } from "./customPanel";

const builder = new DashboardBuilder('Custom panel type')
    .uid('test-custom-panel-type')

    .refresh('1m')
    .time({ from: 'now-30m', to: 'now' })

    .withRow(new RowBuilder('Overview'))
    .withPanel(
        new CustomPanelBuilder()
            .title('Sample custom panel')
            .makeBeautiful()
    );

console.log(JSON.stringify(builder.build(), null, 2));
```

## 成熟度

此寄存器中的代码应被视为"公开预览". 虽然Grafana Labs在生产中使用了它,但它仍在积极开发中.

> \[注\] 虫子和问题完全由工程小组处理。 没有待命支助或苏丹解放军.

## 许可证

[Apache 2.0 许可证](https://npmcn.com/package/%40grafana/grafana-foundation-sdk/LICENSE)

## 常见问题

### @grafana/grafana-foundation-sdk 是什么？

一套用于构建和操纵Grafana对象的工具,类型和库\.

### 如何安装 @grafana/grafana-foundation-sdk？

在项目目录运行 npm install @grafana/grafana-foundation-sdk，或使用 pnpm add / yarn add / bun add。

### @grafana/grafana-foundation-sdk 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @grafana/grafana-foundation-sdk 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @grafana/grafana-foundation-sdk 可以商用吗？

@grafana/grafana-foundation-sdk 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @grafana/grafana-foundation-sdk 的下载量有多少？

根据 npm 官方下载统计，@grafana/grafana-foundation-sdk 在 2026/10/17 – 2026/11/15 这 30 天内被下载 791,005 次，日均约 26,367 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @grafana/grafana-foundation-sdk 还在维护吗？

最新版本 0\.0\.22 发布于 2026/10/29（18 天前）；至今共发布 432 个版本，其中过去 12 个月发布了 31 个；首次发布于 2023/12/08。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

