Установка
Настройка
Шаблон для Vue
Начните с одного из официальных шаблонов: кнопка Use this template на GitHub или командная строка:
git clone https://github.com/bitrix24/templates-dashboard-vue.git <project-name>
cd <project-name>
pnpm install
pnpm run dev
git clone https://github.com/bitrix24/starter-b24ui-vue.git <project-name>
cd <project-name>
pnpm install
pnpm run dev
<project-name> — имя каталога, в котором будет создан проект. Замените его названием вашего проекта.Добавление в проект на Vue
Установите пакет Bitrix24 UI
pnpm add @bxshefby/b24ui-nuxt @bitrix24/b24icons-vue tailwindcss
yarn add @bxshefby/b24ui-nuxt @bitrix24/b24icons-vue tailwindcss
npm install @bxshefby/b24ui-nuxt @bitrix24/b24icons-vue tailwindcss
bun add @bxshefby/b24ui-nuxt @bitrix24/b24icons-vue tailwindcss
@bitrix24 переводится на @bxshefby/b24ui-nuxt псевдонимом в package.json или заменой имени.Добавьте плагин Bitrix24 UI для Vite в vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
bitrix24UIPluginVite()
]
})
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
import laravel from 'laravel-vite-plugin'
export default defineConfig({
plugins: [
laravel({
input: ['resources/js/app.ts'],
refresh: true
}),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false
}
}
}),
bitrix24UIPluginVite({
router: 'inertia'
})
]
})
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
import adonisjs from '@adonisjs/vite/client'
import inertia from '@adonisjs/inertia/client'
export default defineConfig({
plugins: [
adonisjs({
entrypoints: ['inertia/app/app.ts'],
reload: ['resources/views/**/*.edge']
}),
inertia(),
vue(),
bitrix24UIPluginVite({
router: 'inertia'
})
]
})
unplugin-auto-import и unplugin-vue-components, которые создают файлы деклараций типов auto-imports.d.ts и components.d.ts. Скорее всего, их стоит добавить в .gitignore и в tsconfig.{
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "auto-imports.d.ts", "components.d.ts"]
}
# Автоматически созданные декларации типов
auto-imports.d.ts
components.d.ts
build из шаблона create-vue запускает vue-tsc параллельно с vite build (run-p type-check "build-only {@}"), поэтому в чистой копии проверка типов может начаться раньше, чем файлы появятся, и завершиться ошибкой вроде Cannot find name 'useToast'. Запускайте проверку типов после сборки, чтобы декларации успели создаться.{
"scripts": {
"build": "run-s build-only type-check"
}
}
tsconfig, чтобы в vite.config.ts работало автодополнение.{
"compilerOptions": {
"paths": {
"#build/b24ui": [
"./node_modules/.b24ui-nuxt/b24ui"
]
}
}
}
{
"compilerOptions": {
"paths": {
"#build/b24ui/*": [
"./node_modules/.b24ui-nuxt/b24ui/*"
]
}
}
}
Подключите Vue-плагин Bitrix24 UI
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import b24UiPlugin from '@bxshefby/b24ui-nuxt/vue-plugin'
import App from './App.vue'
const app = createApp(App)
const router = createRouter({
routes: [],
history: createWebHistory()
})
app.use(router)
app.use(b24UiPlugin)
app.mount('#app')
import type { DefineComponent } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'
import b24UiPlugin from '@bxshefby/b24ui-nuxt/vue-plugin'
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'
import { createApp, h } from 'vue'
const appName = import.meta.env.VITE_APP_NAME || 'Laravel x Bitrix24 UI'
createInertiaApp({
title: title => (title ? `${title} - ${appName}` : appName),
resolve: name =>
resolvePageComponent(
`./pages/${name}.vue`,
import.meta.glob<DefineComponent>('./pages/**/*.vue')
),
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.use(b24UiPlugin)
.mount(el)
}
})
import type { DefineComponent } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'
import b24UiPlugin from '@bxshefby/b24ui-nuxt/vue-plugin'
import { resolvePageComponent } from '@adonisjs/inertia/helpers'
import { createApp, h } from 'vue'
const appName = import.meta.env.VITE_APP_NAME || 'AdonisJS x Bitrix24 UI'
createInertiaApp({
title: title => (title ? `${title} - ${appName}` : appName),
resolve: name =>
resolvePageComponent(
`../pages/${name}.vue`,
import.meta.glob<DefineComponent>('../pages/**/*.vue')
),
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.use(b24UiPlugin)
.mount(el)
}
})
Подключите Tailwind CSS и Bitrix24 UI в CSS
@import "tailwindcss";
@import "@bxshefby/b24ui-nuxt";
@import "tailwindcss";
@import "@bxshefby/b24ui-nuxt";
@import "tailwindcss";
@import "@bxshefby/b24ui-nuxt";
import './assets/css/main.css'
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import b24UiPlugin from '@bxshefby/b24ui-nuxt/vue-plugin'
import App from './App.vue'
const app = createApp(App)
const router = createRouter({
routes: [],
history: createWebHistory()
})
app.use(router)
app.use(b24UiPlugin)
app.mount('#app')
import '../css/app.css'
import type { DefineComponent } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'
import b24UiPlugin from '@bxshefby/b24ui-nuxt/vue-plugin'
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'
import { createApp, h } from 'vue'
const appName = import.meta.env.VITE_APP_NAME || 'Laravel x Bitrix24 UI'
createInertiaApp({
title: title => (title ? `${title} - ${appName}` : appName),
resolve: name =>
resolvePageComponent(
`./pages/${name}.vue`,
import.meta.glob<DefineComponent>('./pages/**/*.vue')
),
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.use(b24UiPlugin)
.mount(el)
}
})
import '../css/app.css'
import type { DefineComponent } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'
import b24UiPlugin from '@bxshefby/b24ui-nuxt/vue-plugin'
import { resolvePageComponent } from '@adonisjs/inertia/helpers'
import { createApp, h } from 'vue'
const appName = import.meta.env.VITE_APP_NAME || 'AdonisJS x Bitrix24 UI'
createInertiaApp({
title: title => (title ? `${title} - ${appName}` : appName),
resolve: name =>
resolvePageComponent(
`../pages/${name}.vue`,
import.meta.glob<DefineComponent>('../pages/**/*.vue')
),
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.use(b24UiPlugin)
.mount(el)
}
})
{
"files.associations": {
"*.css": "tailwindcss"
},
"editor.quickSuggestions": {
"strings": "on"
},
"tailwindCSS.classAttributes": ["class", "b24ui"],
"tailwindCSS.classFunctions": ["defineAppConfig"]
}
Оберните приложение в компонент App
<template>
<B24App>
<RouterView />
</B24App>
</template>
<template>
<B24App>
<!-- Здесь ваше содержимое -->
</B24App>
</template>
<template>
<B24App>
<!-- Здесь ваше содержимое -->
</B24App>
</template>
App задаёт глобальные настройки. Без него не работают Toast, Tooltip и программные оверлеи.Добавьте класс isolate корневому контейнеру
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bitrix24 UI</title>
</head>
<body>
<div id="app" class="isolate"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
@inertiaHead
@vite('resources/js/app.ts')
</head>
<body>
<div class="isolate">
@inertia
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
@inertiaHead()
@vite(['inertia/app/app.ts', `inertia/pages/${page.component}.vue`])
</head>
<body>
@inertia({ class: 'isolate' })
</body>
</html>
Опции
Bitrix24 UI настраивается опциями в vite.config.ts.
colorMode
Опция colorMode включает или отключает интеграцию цветовой схемы из @vueuse/core.
- По умолчанию:
true
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
bitrix24UIPluginVite({
colorMode: false
})
]
})
theme.unstyled
Опция theme.unstyled убирает из компонентов все классы темы по умолчанию. Остаются только их структура и классы, которые вы передаёте через class, b24ui или app.config.b24ui.
- По умолчанию:
false
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
bitrix24UIPluginVite({
theme: {
unstyled: true
}
})
]
})
Modal, Drawer или Calendar, раскладку придётся задать самостоятельно — как в unstyled-режиме PrimeVue.theme.prefix
Опция theme.prefix задаёт тот же префикс, что и в импорте Tailwind CSS. Так компоненты Bitrix24 UI используют правильные утилитарные классы и CSS-переменные с префиксом.
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
bitrix24UIPluginVite({
theme: {
prefix: 'tw'
}
})
]
})
@import "tailwindcss" prefix(tw);
@import "@bxshefby/b24ui-nuxt";
Префикс автоматически добавляется ко всем утилитарным классам Tailwind и CSS-переменным в темах компонентов Bitrix24 UI:
<!-- Без префикса -->
<button class="px-2 py-1 text-xs hover:bg-red-500/75">Button</button>
<!-- С префиксом tw -->
<button class="tw:px-2 tw:py-1 tw:text-xs tw:hover:bg-red-500/75">Button</button>
prose
Опция prose включает компоненты <Prose> из Bitrix24 UI и их тему.
- По умолчанию:
true
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
bitrix24UIPluginVite({
prose: false
})
]
})
autoImport
Опция autoImport отключает автоимпорт композаблов или настраивает параметры unplugin-auto-import.
- По умолчанию:
{}
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
ui({
autoImport: false
})
]
})
@bxshefby/b24ui-nuxt/composables.components
Опция components отключает автоимпорт компонентов или настраивает параметры unplugin-vue-components.
- По умолчанию:
{}
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
bitrix24UIPluginVite({
components: false
})
]
})
import Button from '@bxshefby/b24ui-nuxt/components/Button.vue' or import ProseCode from '@bxshefby/b24ui-nuxt/components/prose/Code.vue'.router
Опция router настраивает интеграцию с маршрутизацией. Она нужна приложениям без vue-router: Electron-приложениям, MPA и фреймворкам вроде Inertia.js или Hybridly.
- По умолчанию:
true
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
bitrix24UIPluginVite({
router: false
})
]
})
router: false в конфигурации Vite и передайте функцию при подключении Vue-плагина:import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
import { router } from 'hybridly'
app.use(bitrix24UIPluginVite, {
router: (event, { href, external }) => {
if (external) {
return
}
event.preventDefault()
router.navigate({ url: href })
}
})
false или 'inertia'vue-router как зависимость не нужен.scanPackages
Опция scanPackages задаёт дополнительные npm-пакеты, в которых нужно искать компоненты Bitrix24 UI. Она полезна, если у вас есть общая библиотека компонентов, использующая компоненты Bitrix24 UI внутри.
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
bitrix24UIPluginVite({
scanPackages: ['@my-org/b24ui-components']
})
]
})
@bxshefby/b24ui-nuxt. Используйте опцию, если во внешних пакетах есть Vue-компоненты, которые используют Bitrix24 UI.root
Опция root переопределяет каталог, в котором Bitrix24 UI создаёт каталог .b24ui-nuxt (шаблоны темы). По умолчанию берётся root из Vite, но в таких сборках, как electron-vite, root рендерера указывает на подкаталог (например, src/renderer). Тогда шаблоны попадают в src/renderer/node_modules/.b24ui-nuxt, куда Tailwind не заглядывает, и классы темы пропадают.
import { defineConfig } from 'electron-vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
renderer: {
root: 'src/renderer',
plugins: [
vue(),
bitrix24UIPluginVite({
root: __dirname
})
]
}
})
root корень проекта, чтобы созданный каталог .b24ui-nuxt оказался в node_modules, который сканирует Tailwind.experimental.componentDetection 2.12+
Опция experimental.componentDetection включает автоматическое определение компонентов для tree-shaking. Исходный код сканируется, находятся реально используемые компоненты, и CSS генерируется только для них (вместе с их зависимостями). Без опции плагин Vite генерирует CSS темы для каждого компонента. Определение охватывает корень Vite, пакеты из scanPackages и все dirs из опции components, лежащие вне корня.
- По умолчанию:
false - Тип:
boolean | string[]
Включить автоматическое определение:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
bitrix24UIPluginVite({
experimental: {
componentDetection: true
}
})
]
})
Добавить компоненты для динамического использования:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bxshefby/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
bitrix24UIPluginVite({
experimental: {
componentDetection: ['Modal', 'DropdownMenu', 'Popover']
}
})
]
})
<component :is="..." />, которые нельзя проанализировать статически. Имя, не принадлежащее компоненту, приводит к предупреждению, а не игнорируется молча.