@divkitframework/divkit

中文文档
33.11.0发布于 2026/11/09Apache-2.0TypeScriptESM + CJS零依赖近 30 天下载 1.5万

DivKit for the web

原始使用文档
文档目录18 节
  1. DivKit for the Web
  2. Installation
  3. Usage
  4. Inlude CSS
  5. Include js
  6. Is there any server-side rendering (SSR) or will it be only…
  7. Are you want to use ES module or CommonJS module?
  8. Use in the browser via global variables without build:
  9. Usage with React
  10. TypeScript and types
  11. Browser/Node.js support
  12. API: render
  13. extensions
  14. extensionsForAllComponents
  15. customComponents
  16. Palette support (DEPRECATED)
  17. API: other
  18. Note about 64-bit integers

DivKit for the Web

client code size

Installation

npm i @divkitframework/divkit --save

Usage

Example usage repos

Inlude CSS

[!IMPORTANT] For all variants of usage, css file dist/client.css is required. Include it in any way (import as module, link directly in html, etc).

Include js

JS code can be bundled with various strategies. Basically you need to answer a few questions

Is there any server-side rendering (SSR) or will it be only on client?

SSR + hydration

On the server side there is /server module:

import {render} from '@divkitframework/divkit/server';

const html = render({
    id: 'smth',
    json: {
        card: {},
        templates: {}
    },
    onError(details) {
        console.error(details.error);
    }
});

Then use /client-hydratable on client to hydrate server-side html::

import {render} from '@divkitframework/divkit/client-hydratable';

render({
    id: 'smth',
    target: document.querySelector('#root'),
    hydrate: true,
    json: {
        card: {},
        templates: {}
    },
    onError(details) {
        console.error(details.error);
    }
});

Client-only rendering

For the client-only usage there is /client module. The size of this module is slightly smaller than /client-hydratable.

import {render} from '@divkitframework/divkit/client';

render({
    id: 'smth',
    target: document.querySelector('#root'),
    json: {
        card: {},
        templates: {}
    },
    onError(details) {
        console.error(details.error);
    }
});

Are you want to use ES module or CommonJS module?

The package contains both of them.

Node.js will automatically use the appropriate version.

Webpack or other bundles will use ES modules version.

For the direct CommonJS usage, this files can be used:

dist/client.js
dist/client-hydratable.js
dist/server.js

ES modules files:

dist/esm/client.mjs
dist/esm/client-hydratable.mjs
dist/esm/server.mjs

ES modules can be used in the browser directly without any build, but build is strongly encouraged.:

<script type="module">
    import {render} from './node_modules/@divkitframework/divkit/dist/esm/client.mjs';

    render({
        id: 'smth',
        target: document.querySelector('#root'),
        json: {
            card: {},
            templates: {}
        },
        onError(details) {
            console.error(details.error);
        }
    });
</script>

Use in the browser via global variables without build:

<script src="./node_modules/@divkitframework/divkit/dist/browser/client.js"></script>
<script>
    window.Ya.DivKit.render({
        id: 'smth',
        target: document.querySelector('#root'),
        json: {
            card: {},
            templates: {}
        },
        onError(details) {
            console.error(details.error);
        }
    });
</script>

[!IMPORTANT] Older versions of DivKit uses the syntax Ya.Divkit. It is now deprecated and should not be used.

Usage with React

There is a separate package for that.

React component package

TypeScript and types

All modules have typescript definitions (client, client-hydratable and server), so typescript will load them at any use.

Browser/Node.js support

Browser support

chrome >= 67
safari >= 14
firefox >= 68

However, some rare features require more modern browsers, for example, aspect for a container requires aspect-ratio support in css. Such requirements are described in the documentation.

Node.js

Node.js >= 14

API: render

All 3 exported modules have an exported function render. This function works in a similar way on client and server.

/client and /client-hydratable requires option target - an HTML-element that is used to render json.

Instead, /server module will return an HTML string.

id

String, required.

Means the unique block identifier. Used to generate ids and classes. There should not be 2 blocks with the same id on the page.

json

Object, required.

Divjson itself.

target

/client and /client-hydratable

HTML-element, required.

hydrate

/client-hydratable

Boolean, optional.

It must be true, if the current render must hydrate html in target.

onError

Function, optional.

Callback for errors and warnings for manual processing.

function onError(detauls: {
    error: Error & {
        level: 'error' | 'warn';
        additional: Record<string, unknown>;
    };
}) {
    console.log(error.level, error.additional, error.message);
}

onStat

/client and /client-hydratable

Function, optional.

Used for logging clicks (for elements with action) and visibility logging (for elements with visibility_action(s) and disappear_actions).

function onStat(details: {
    type: 'click' | 'visible' | 'disappear' | 'trigger';
    action: Action | VisibilityAction | DisappearAction;
}) {
}

onCustomAction

/client and /client-hydratable

Function, optional.

Callback for a component with an action that contains non-standard protocols.

function onCustomAction(action: Action): void {
}

typefaceProvider

Function, optional.

Callback for a custom font-family css property value.

function typefaceProvider(fontFamily: string, opts?: {
    fontWeight?: number;
}): string {
}

fetchInit

/client and /client-hydratable

Function or object, optional.

It is used as the second parameter for the fetch requests in the download and submit actions.

function fetchInit(url: string) {
    return {
        credentials: 'include'
    };
}

Or

fetchInit: {
    credentials: 'include'
}

onSubmit

/client and /client-hydratable

Function, optional.

It is used to process the submit actions. If it is not specified, fetch() is used by default.

function onSubmit(action: ActionSubmit, values: Record<string, unknown>): Promise<void> {
    return fetch(action.reqeust.url, {
        body: JSON.stringify(values)
    });
}

platform

desktop | touch | auto

The default value is auto. Tweaks for mouse or touch events.

direction

ltr | rtl

The default value is ltr. This will set the direction of the text and layout inside the markup (the html dir attribute). This property changes the behaviour of start / end and other properties and values.

mix

String, optional.

An additional class added to the root element.

customization

Object, optional.

Currently supported properties:

  • galleryLeftClass — left scroll button class on desktop for the gallery
  • galleryRightClass — right scroll button class on desktop for the gallery
  • pagerLeftClass — left scroll button class on desktop for the pager
  • pagerRightClass — right scroll button class on desktop for the pager
  • menuPopupClass — class for the menu popup
  • menuItemClass — class for the menu item

builtinProtocols

String array, optional. Default value is ['http', 'https', 'tel', 'mailto', 'intent']

Components with an action containing a protocol from the list will be rendered as <a>, and clicking on them will be processed by the browser. Protocols outside the list will cause the element to be rendered as a button-like, and clicking on them causes an 'onCustomAction'.

tooltipRoot

/client and /client-hydratable

HTMLElement, optional.

Allows to attach tooltips and menus to the custom root, outside of target. Useful to avoid cropping.

extensions

Map<string, DivExtensionClass>, optional.

Allows to modify components behaviour by a custom code. DivKit contains several built-in extensions, that can be enabled with this property.

Extensions are client-side only. One can render some json on a server, than hydrate it on a client with extensions, but if these extensions modify components look, users may notice this change on a page load.

Also be aware of new releases (even minor and patch versions). Built-in extensions will remain compatible with the new code, but a custom ones can broke with it. Simple extenions, like setting attributes on a component DOM-node less likely broke, but a heavier ones, that depends on a DOM tree, tag names, events or something are on your own risk.

Enabling built-in extensions

Building of a new extension

extensionsForAllComponents

DivExtensionRegistration[], optional, defaults to []. Each entry is a DivExtensionClass or { Extension: DivExtensionClass, params?: object, id?: string }.

Applies each extension to every rendered component without an extensions entry in JSON. Uses the same DivExtension interface as extensions: a separate instance is created for each component DOM node, with the registration's params object passed directly to its constructor. Bare classes and registrations without params receive an empty object. Parameters are host-provided values; DivKit does not evaluate JSON expressions in them. Like extensions, this option is client-side only.

render({
    target,
    id: 'card',
    json,
    extensionsForAllComponents: [
        HoverNotifier,
        { Extension: HoverNotifier, params: { label: 'debug' } }
    ]
});

To receive extension_action, provide an id in the registration and implement handleAction. The action's extension_id selects that registration, and div_id selects the component; no JSON extension declaration is required. Registrations without an id still receive lifecycle callbacks but cannot be addressed by actions. For a shared ID, JSON extension handlers run first, followed by handlers from extensionsForAllComponents in registration order, stopping when a handler returns true (including an awaited result).

customComponents

Map<string, CustomComponentDescription>, optional.

Custom components can be provided using the customComponents map. This structure maps names from json markup to html custom elements (or web components).

These components can provide any additional features that your application needs, such as map widgets, integration into social networks, YouTube videos, and so on.

Custom components is supported not only on the client side, but also on the server side. See the examples below for more detailed information:

Simple custom component

Custom component with the DivKit items

Custom component and SSR

Custom component extended api

store

Object, optional.

Additional external storage. The get and set methods should be implemented.

Please note that these methods must be synchronous! DivKit does not have asynchronous render methods, so any get function cannot be asynchronous. It is possible to process set asynchronously, but if the value from get is critical for you and cannot be read synchronously, you must read it before calling render.

weekStartDay

Number, optional. 0 by default.

Affects the formatting of dates.

pagerChildrenClipEnabled

Boolean, optional. true by default.

Whether cropping is enabled in the pager elements. It can be useful in cases with shadow elements.

pagerMouseDragEnabled

Boolean, optional. true by default.

Whether dragging pager elements with the mouse is enabled or not.

videoPlayerProvider

Object, optional.

A provider for implementing a custom video player. On the server side, the videoPlayerProvider must contain the template property, which is a string or a markup provider function for the video player. On the client side, the videoPlayerProvider must contain an instance function that creates an instance of the player.

theme

system | light | dark

The default value is system. Affects variables in palette and the themeVariableName variable.

themeVariableName

String, optional.

When set, this property creates a variable that stores the current theme (light or dark).

Palette support (DEPRECATED)

This feature will be removed in the future.

Divjson along with the card and templates can contain a palette property with colors for light and dark themes:

{
    "card": {
        "states": [
            {
                "div": {
                    "type": "text",
                    "text": "Hello palette",
                    "text_color": "@{text}",
                    "background": [{
                        "type": "solid",
                        "color": "@{bg}"
                    }]
                },
                "state_id": 0
            }
        ],
        "log_id": "test"
    },
    "templates": {},
    "palette": {
        "dark": [
            {
                "name": "bg",
                "color": "#000"
            },
            {
                "name": "text",
                "color": "#fff"
            }
        ],
        "light": [
            {
                "name": "bg",
                "color": "#fff"
            },
            {
                "name": "text",
                "color": "#000"
            }
        ]
    }
}

The theme can be changed at any time:

instance.setTheme('dark');

API: other

Variables

import {createVariable, createGlobalVariablesController, render} from '@divkitframework/divkit';

// Custom variable outside of DivJson
const variable = createVariable('name', 'string', 'val');

variable.subscribe(newVal => {
    console.log(newVal);
});

// Custom scope for variables
const controller = createGlobalVariablesController();

controller.setVariable(variable);

render(({
    id: 'smth',
    target: document.querySelector('#root'),
    json: {},
    globalVariablesController: controller
});

setData (EXPERIMENTAL)

This methods allows you to quckly redraw the DivKit card:

instance.setData({
    ...
});

Some notes:

  • This method is experimental, its logic and api may be changed the future versions.
  • setData doesn't change any existing variables or variable triggers. It will onky create new variables. This is intentional.
  • This method will try to do as little work as possible and will try to preserve the state of the card (input values and so on).

Note about 64-bit integers

DivKit internally uses the BigInt type if the current platform supports it (both client-side and server-side). This means that on unsupported platforms, integers will lose precision if the value exceeds 2^53.

Note that built-in functions like JSON.parse and .json() will parse large values, but the result type will be number, not bigint. So, for example, if someone fetches data from the server, the values may lose accuracy outside the DivKit library.


Documentation. Medium tutorial. Habr tutorial.

Telegram: English-speaking chat | Чат на русском.

版本与发布记录

@divkitframework/divkit 共发布 437 个版本,首次发布于 2022/08/26;过去 12 个月发布了 75 个版本。

版本发布日期距今
33.11.0latest2026/11/092 天前
33.10.0-canary-0a27c8fe92183dc935615402bf1ce542a1887e41canary2026/11/048 天前
33.10.02026/11/029 天前
33.10.0-canary-408a3da173bc98ff2bb545f269bcfe40b7e299062026/10/3112 天前
33.10.0-canary-780977f65c1f0cb839337032501c451c65eb11f72026/10/3112 天前
33.9.02026/10/2715 天前

关于 @divkitframework/divkit 的常见问题

@divkitframework/divkit 是什么?

DivKit for the web

如何安装 @divkitframework/divkit?

在项目目录运行 npm install @divkitframework/divkit,或使用 pnpm add / yarn add / bun add。

@divkitframework/divkit 支持 TypeScript 吗?

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

@divkitframework/divkit 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@divkitframework/divkit 可以商用吗?

@divkitframework/divkit 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@divkitframework/divkit 的下载量有多少?

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

@divkitframework/divkit 还在维护吗?

最新版本 33.11.0 发布于 2026/11/09(2 天前);至今共发布 437 个版本,其中过去 12 个月发布了 75 个;首次发布于 2022/08/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。