feat .calude

This commit is contained in:
Ironsp
2026-09-17 08:52:53 +08:00
parent a84f7c4906
commit e1750b16c4
363 changed files with 41250 additions and 2 deletions

View File

@@ -0,0 +1,5 @@
# Generation Info
- **Source:** `sources/uni-helper`
- **Git SHA:** `286d8656dc077a7d9d6a50e647284ff1ea48ac6b`
- **Generated:** 2026-01-30

View File

@@ -0,0 +1,88 @@
---
name: uni-helper
description: Comprehensive skill reference for uni-helper ecosystem - AI-powered development tools for uni-app
metadata:
author: FlippeDround
version: "2026.1.30"
source: Generated from https://github.com/uni-helper/website, skills located at https://github.com/uni-helper/ai-tools
---
> The skill is based on uni-helper documentation, generated at 2026-01-30.
uni-helper is an ecosystem of AI-powered development tools for uni-app, providing Vite plugins, utility libraries, TypeScript support, and development tools to enhance the uni-app development experience.
## Vite Plugins
| Topic | Description | Reference |
|-------|-------------|-----------|
| vite-plugin-uni-pages | File-based routing system for uni-app with auto page discovery | [plugin-pages](references/plugin-pages.md) |
| vite-plugin-uni-layouts | Nuxt-like layouts system for uni-app | [plugin-layouts](references/plugin-layouts.md) |
| vite-plugin-uni-components | On-demand automatic component imports | [plugin-components](references/plugin-components.md) |
| vite-plugin-uni-manifest | Write manifest.json in TypeScript | [plugin-manifest](references/plugin-manifest.md) |
| vite-plugin-uni-platform | File-based platform compilation (*.h5|mp-weixin|app.*) | [plugin-platform](references/plugin-platform.md) |
| vite-plugin-uni-platform-modifier | Platform modifiers for attributes/directives | [plugin-platform-modifier](references/plugin-platform-modifier.md) |
| vite-plugin-uni-middleware | Middleware support for uni-app routing | [plugin-middleware](references/plugin-middleware.md) |
## Libraries
| Topic | Description | Reference |
|-------|-------------|-----------|
| uni-use | VueUse-style composable utilities for uni-app | [lib-uni-use](references/lib-uni-use.md) |
| uni-network | Promise-based HTTP client for uni-app | [lib-uni-network](references/lib-uni-network.md) |
| uni-promises | Promise wrappers for uni-app APIs | [lib-uni-promises](references/lib-uni-promises.md) |
| uni-typed | TypeScript type definitions for uni-app templates | [lib-uni-typed](references/lib-uni-typed.md) |
## Utilities
| Topic | Description | Reference |
|-------|-------------|-----------|
| uni-env | Environment detection utilities for uni-app | [util-uni-env](references/util-uni-env.md) |
| unocss-preset-uni | UnoCSS preset for uni-app | [util-unocss-preset](references/util-unocss-preset.md) |
## Project Starters
| Topic | Description | Reference |
|-------|-------------|-----------|
| create-uni | CLI scaffolding tool for uni-app projects | [starter-create-uni](references/starter-create-uni.md) |
| vitesse-uni-app | Vite-powered uni-app starter template | [starter-vitesse](references/starter-vitesse.md) |
## Plugin Order Best Practices
When using multiple uni-helper Vite plugins, the recommended order is:
```ts
// vite.config.ts
export default defineConfig({
plugins: [
UniComponents(), // 1. Component auto-import
UniPages(), // 2. File-based routing
UniLayouts(), // 3. Layout system
UniManifest(), // 4. Manifest generation
UniPlatform(), // 5. Platform-specific files
UniPlatformModifier(), // 6. Platform modifiers
UniMiddleware(), // 7. Route middleware
Uni(), // 8. Official uni-app plugin (always last)
],
})
```
## Quick Start
Create a new uni-app project with create-uni:
```bash
# npm 7+, extra double-dash is needed
npm create uni@latest
# pnpm
pnpm create uni
# yarn
yarn create uni
```
## Official Resources
- Website: https://uni-helper.js.org
- GitHub: https://github.com/uni-helper
- NPM Scope: @uni-helper

View File

@@ -0,0 +1,221 @@
---
name: uni-network
description: Promise-based HTTP client for uni-app - axios-inspired API with uni.request as default transport
---
# uni-network
Promise-based HTTP client for uni-app, inspired by axios@0.27.2. Uses uni.request/uni.uploadFile/uni.downloadFile as the underlying transport.
## Installation
```bash
npm i @uni-helper/uni-network
```
## Features
- Promise-based API
- Request/response interceptors
- Request cancellation
- TypeScript support
- Composition API integration
- Upload/download support
## Basic Usage
```ts
import { un } from '@uni-helper/uni-network'
// GET request
un('/user/123')
// POST request
un({
method: 'POST',
url: '/user/123',
data: {
firstName: 'Fred',
lastName: 'Flintstone',
},
})
```
## Request Aliases
```ts
import { un } from '@uni-helper/uni-network'
// HTTP verbs
un.get('/users')
un.post('/users', { name: 'John' })
un.put('/users/1', { name: 'Jane' })
un.patch('/users/1', { age: 30 })
un.delete('/users/1')
// Upload/download
un.upload({
url: '/upload',
filePath: tempFilePath,
name: 'file',
})
un.download({
url: '/files/report.pdf',
})
```
## Creating an Instance
```ts
import { createUniNetwork } from '@uni-helper/uni-network'
const http = createUniNetwork({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
})
// Use the instance
http.get('/users')
```
## Interceptors
```ts
import { un } from '@uni-helper/uni-network'
// Request interceptor
un.interceptors.request.use(
(config) => {
// Add auth token
const token = uni.getStorageSync('token')
if (token) {
config.headers = config.headers || {}
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error) => {
return Promise.reject(error)
}
)
// Response interceptor
un.interceptors.response.use(
(response) => {
// Transform response data
return response.data
},
(error) => {
// Handle errors globally
if (error.statusCode === 401) {
uni.redirectTo({ url: '/pages/login/index' })
}
return Promise.reject(error)
}
)
```
## Configuration
```ts
interface UniNetworkConfig {
// URL
url?: string
// Base URL
baseURL?: string
// Method
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | ...
// Headers
headers?: Record<string, string>
// Request data
data?: any
// Query params
params?: Record<string, any>
// Timeout in ms
timeout?: number
// Response type
responseType?: 'text' | 'arraybuffer'
// Data type
dataType?: 'json' | 'string'
// Enable http2
enableHttp2?: boolean
// Enable quic
enableQuic?: boolean
// Enable cache
enableCache?: boolean
// SSL verify
sslVerify?: boolean
}
```
## Request Cancellation
```ts
import { un } from '@uni-helper/uni-network'
const controller = new AbortController()
un.get('/long-request', {
signal: controller.signal,
})
// Cancel after 5 seconds
setTimeout(() => {
controller.abort()
}, 5000)
```
## Error Handling
```ts
import { un, UniNetworkError } from '@uni-helper/uni-network'
try {
const response = await un.get('/users')
} catch (error) {
if (error instanceof UniNetworkError) {
console.log('Request failed:', error.message)
console.log('Status:', error.statusCode)
}
}
```
## Composition API
```ts
import { useUniNetwork } from '@uni-helper/uni-network'
const { data, error, loading, execute } = useUniNetwork({
url: '/users',
method: 'GET',
})
// Execute manually
await execute()
```
## TypeScript Support
```ts
import { un } from '@uni-helper/uni-network'
interface User {
id: number
name: string
email: string
}
// Typed response
const { data } = await un.get<User>('/users/1')
console.log(data.name) // Type-safe access
```
<!--
Source references:
- https://github.com/uni-helper/uni-network
- https://uni-helper.js.org/uni-network
-->

View File

@@ -0,0 +1,197 @@
---
name: uni-promises
description: Promise wrappers for uni-app APIs - convert callback-based APIs to Promise-based
---
# uni-promises
Promise wrappers for uni-app's callback-based APIs. Convert uni-app APIs to return Promises for better async/await support.
## Installation
```bash
npm i @uni-helper/uni-promises
```
## Usage
Instead of using callbacks:
```ts
// Original callback style
uni.request({
url: 'https://api.example.com',
success: (res) => {
console.log(res.data)
},
fail: (err) => {
console.error(err)
},
})
```
Use Promises:
```ts
import { request } from '@uni-helper/uni-promises'
// Promise style
const res = await request({
url: 'https://api.example.com',
})
console.log(res.data)
```
## Available APIs
Most uni-app APIs are wrapped:
### Network
- `request` - HTTP request
- `uploadFile` - File upload
- `downloadFile` - File download
- `connectSocket` - WebSocket
### Storage
- `setStorage` - Set storage
- `getStorage` - Get storage
- `removeStorage` - Remove storage
- `clearStorage` - Clear all storage
- `getStorageInfo` - Storage info
### Media
- `chooseImage` - Select images
- `chooseVideo` - Select video
- `chooseMedia` - Select media
- `previewImage` - Preview images
- `saveImageToPhotosAlbum` - Save image
- `compressImage` - Compress image
### File
- `saveFile` - Save file
- `getFileInfo` - File info
- `getSavedFileList` - Saved files list
- `removeSavedFile` - Remove saved file
- `openDocument` - Open document
### Location
- `getLocation` - Get location
- `chooseLocation` - Choose location
- `openLocation` - Open location
### Device
- `getSystemInfo` - System info
- `getNetworkType` - Network type
- `scanCode` - QR/barcode scan
- `setClipboardData` - Copy to clipboard
- `getClipboardData` - Get clipboard
### UI
- `showToast` - Show toast
- `showModal` - Show modal
- `showActionSheet` - Show action sheet
- `showLoading` - Show loading
- `hideLoading` - Hide loading
- `showNavigationBarLoading` - Nav loading
- `hideNavigationBarLoading` - Hide nav loading
- `setNavigationBarTitle` - Set nav title
- `setNavigationBarColor` - Set nav color
- `pageScrollTo` - Scroll to position
### Navigation
- `navigateTo` - Navigate to page
- `redirectTo` - Redirect to page
- `reLaunch` - Re-launch app
- `switchTab` - Switch tab
- `navigateBack` - Go back
### Login
- `login` - User login
- `checkSession` - Check session
- `getUserProfile` - Get user profile
- `getUserInfo` - Get user info
### Payment
- `requestPayment` - Request payment
## Example Usage
```ts
import {
showModal,
showToast,
getStorage,
navigateTo,
getSystemInfo,
chooseImage,
uploadFile,
} from '@uni-helper/uni-promises'
async function handleUserAction() {
// Show confirmation
const { confirm } = await showModal({
title: 'Confirm',
content: 'Are you sure?',
})
if (!confirm) return
try {
// Get cached data
const { data: token } = await getStorage({ key: 'token' })
// Get system info
const systemInfo = await getSystemInfo()
console.log('Platform:', systemInfo.platform)
// Select image
const { tempFilePaths } = await chooseImage({
count: 1,
sizeType: ['compressed'],
})
// Upload file
const uploadRes = await uploadFile({
url: 'https://api.example.com/upload',
filePath: tempFilePaths[0],
name: 'file',
})
await showToast({
title: 'Success!',
icon: 'success',
})
// Navigate
await navigateTo({
url: '/pages/success/index',
})
} catch (error) {
await showToast({
title: error.message || 'Failed',
icon: 'error',
})
}
}
```
## Error Handling
All wrapped APIs reject with standard Error objects:
```ts
import { request } from '@uni-helper/uni-promises'
try {
const res = await request({ url: 'https://api.example.com' })
} catch (error) {
// error.message contains the fail callback message
console.error('Request failed:', error.message)
}
```
<!--
Source references:
- https://github.com/uni-helper/uni-promises
- https://uni-helper.js.org/uni-promises
-->

View File

@@ -0,0 +1,200 @@
---
name: uni-typed
description: TypeScript type definitions for uni-app templates - complete type safety for uni-app components
---
# uni-typed
TypeScript type definitions for uni-app template sections. Provides complete type safety and IntelliSense for uni-app components.
## Installation
```bash
# For uni-app
npm i -D @uni-helper/uni-app-types
# For uni-ui
npm i -D @uni-helper/uni-ui-types
# For uni-cloud
npm i -D @uni-helper/uni-cloud-types
```
## Setup
### Uni-app Types
```json
// tsconfig.json
{
"compilerOptions": {
"types": ["@uni-helper/uni-app-types"]
}
}
```
### Uni-ui Types
```json
// tsconfig.json
{
"compilerOptions": {
"types": [
"@uni-helper/uni-app-types",
"@uni-helper/uni-ui-types"
]
}
}
```
## Features
- Type-safe template event handlers
- Component prop type checking
- Custom event type definitions
- Ref type inference for components
## Component Types
### Template Type Safety
```vue
<script setup lang="ts">
import { ref } from 'vue'
const inputValue = ref('')
const count = ref(0)
const handleInput = (e: UniHelper.InputOnInputEvent) => {
inputValue.value = e.detail.value
}
const handleChange = (e: UniHelper.SwitchOnChangeEvent) => {
console.log(e.detail.value)
}
</script>
<template>
<!-- Type-safe component usage -->
<input
type="text"
:value="inputValue"
@input="handleInput"
/>
<switch :checked="true" @change="handleChange" />
</template>
```
### Component Ref Types
```vue
<script setup lang="ts">
import { ref, onMounted } from 'vue'
// Type-safe component refs
const videoRef = ref<UniHelper.VideoInstance>()
const mapRef = ref<UniHelper.MapInstance>()
onMounted(() => {
// IntelliSense for component methods
videoRef.value?.play()
videoRef.value?.pause()
videoRef.value?.seek(100)
mapRef.value?.moveToLocation({
latitude: 39.9,
longitude: 116.4,
})
})
</script>
<template>
<video ref="videoRef" src="..." />
<map ref="mapRef" />
</template>
```
## Event Types
### Common Event Types
```ts
// Input events
UniHelper.InputOnInputEvent
UniHelper.InputOnBlurEvent
UniHelper.InputOnFocusEvent
// Form events
UniHelper.SwitchOnChangeEvent
UniHelper.CheckboxOnChangeEvent
UniHelper.RadioOnChangeEvent
UniHelper.PickerOnChangeEvent
UniHelper.SliderOnChangeEvent
// Media events
UniHelper.VideoOnPlayEvent
UniHelper.VideoOnPauseEvent
UniHelper.VideoOnEndedEvent
UniHelper.VideoOnTimeUpdateEvent
// Touch events
UniHelper.ViewOnTouchstartEvent
UniHelper.ViewOnTouchmoveEvent
UniHelper.ViewOnTouchendEvent
UniHelper.ViewOnTapEvent
UniHelper.ViewOnLongpressEvent
// Scroll events
UniHelper.ScrollViewOnScrollEvent
UniHelper.ScrollViewOnScrolltolowerEvent
UniHelper.ScrollViewOnScrolltoupperEvent
```
### Custom Events
Define custom event types for your components:
```vue
<script setup lang="ts">
// Child component
const emit = defineEmits<{
change: [value: string]
submit: [data: { id: number; name: string }]
}>()
</script>
```
```vue
<script setup lang="ts">
// Parent component
import type { MyComponentOnChangeEvent } from './types'
const handleChange = (e: MyComponentOnChangeEvent) => {
console.log(e.detail.value)
}
</script>
<template>
<my-component @change="handleChange" />
</template>
```
## Why uni-typed?
DCloud's `@dcloudio/types` only provides TypeScript support for script sections. uni-typed fills the gap for template section type safety, providing:
- Component prop validation
- Event handler type checking
- Method IntelliSense on component refs
- Better IDE support (VS Code, WebStorm)
## Migration from v0 to v1
See the [migration guide](https://uni-helper.js.org/uni-typed/other/migrate-v0-to-v1) for upgrading instructions.
<!--
Source references:
- https://github.com/uni-helper/uni-typed
- https://uni-helper.js.org/uni-typed
-->

View File

@@ -0,0 +1,185 @@
---
name: uni-use
description: VueUse-style composable utilities for uni-app development
---
# uni-use
VueUse-style composable utilities specifically designed for uni-app. Provides reactive wrappers around uni-app APIs.
## Installation
```bash
npm i @uni-helper/uni-use @vueuse/core@9
```
## Usage
```ts
import { tryOnLoad, useClipboard, useSystemInfo } from '@uni-helper/uni-use'
tryOnLoad(() => {
console.log('Page loaded')
})
const { copy, text } = useClipboard()
const { systemInfo } = useSystemInfo()
```
## Auto Import Setup
```ts
// vite.config.ts
import { uniuseAutoImports } from '@uni-helper/uni-use'
import autoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
autoImport({
imports: [uniuseAutoImports()],
}),
uni(),
],
})
```
## Available Composables
### Lifecycle
| Composable | Description |
|------------|-------------|
| `tryOnLoad` | onLoad with try-catch |
| `tryOnShow` | onShow with try-catch |
| `tryOnHide` | onHide with try-catch |
| `tryOnReady` | onReady with try-catch |
| `tryOnUnload` | onUnload with try-catch |
| `tryOnPullDownRefresh` | onPullDownRefresh with try-catch |
| `tryOnReachBottom` | onReachBottom with try-catch |
| `tryOnPageScroll` | onPageScroll with try-catch |
| `tryOnTabItemTap` | onTabItemTap with try-catch |
### System
| Composable | Description |
|------------|-------------|
| `useSystemInfo` | Reactive system information |
| `useDeviceInfo` | Device information |
| `useWindowInfo` | Window dimensions |
| `useAppTheme` | App theme (dark/light) |
| `useNetworkStatus` | Network connection status |
| `useBattery` | Battery status |
### Storage
| Composable | Description |
|------------|-------------|
| `useStorage` | Reactive local storage |
| `useStorageAsync` | Async storage operations |
### UI
| Composable | Description |
|------------|-------------|
| `useClipboard` | Clipboard operations |
| `useToast` | Toast notifications |
| `useModal` | Modal dialogs |
| `useActionSheet` | Action sheet |
| `useLoading` | Loading indicator |
| `useNavigationBar` | Navigation bar control |
| `usePullDownRefresh` | Pull-to-refresh |
### Location
| Composable | Description |
|------------|-------------|
| `useLocation` | Current location |
| `useChooseLocation` | Location picker |
### Media
| Composable | Description |
|------------|-------------|
| `useImage` | Image operations |
| `useCamera` | Camera access |
| `useRecorder` | Audio recording |
## Example Usage
```vue
<script setup lang="ts">
import { useClipboard, useSystemInfo, useStorage, tryOnLoad } from '@uni-helper/uni-use'
// System info
const { systemInfo, safeArea } = useSystemInfo()
// Clipboard
const { text, copy, isSupported } = useClipboard()
const handleCopy = async () => {
await copy('Hello uni-app')
uni.showToast({ title: 'Copied!' })
}
// Storage
const userToken = useStorage('token', '')
const saveToken = (token: string) => {
userToken.value = token
}
// Lifecycle
tryOnLoad((options) => {
console.log('Page options:', options)
})
</script>
<template>
<view class="page">
<text>Platform: {{ systemInfo.platform }}</text>
<text>Safe area top: {{ safeArea?.top }}px</text>
<button @click="handleCopy">Copy to clipboard</button>
</view>
</template>
```
## Build Configuration
For Vite + Vue3 projects targeting ES6:
```ts
// vite.config.ts
export default defineConfig({
build: {
target: 'es6',
cssTarget: 'chrome61',
},
optimizeDeps: {
exclude: ['vue-demi'],
},
})
```
Add polyfills in `main.ts` if needed:
```ts
// main.ts
import 'core-js/actual/array/iterator'
import 'core-js/actual/promise'
import 'core-js/actual/object/assign'
```
## Limitations
- Mini Program and App environments lack some globals (window, navigator)
- Cannot use top-level await
- Some VueUse features may not work in uni-app
## See Also
- Full API docs: https://uni-helper.js.org/uni-use/apis
- VueUse: https://vueuse.org/
<!--
Source references:
- https://github.com/uni-helper/uni-use
- https://uni-helper.js.org/uni-use
-->

View File

@@ -0,0 +1,93 @@
---
name: vite-plugin-uni-components
description: On-demand automatic component imports for uni-app - derived from unplugin-vue-components
---
# vite-plugin-uni-components
Automatic on-demand component imports for uni-app. Derived from unplugin-vue-components with uni-app specific adaptations.
## Installation
```bash
npm i -D @uni-helper/vite-plugin-uni-components
```
## Setup
```ts
// vite.config.ts
import Uni from '@dcloudio/vite-plugin-uni'
import Components from '@uni-helper/vite-plugin-uni-components'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
Components(), // Must be before Uni()
Uni(),
],
})
```
## Features
- Automatic component imports from `src/components`
- Supports UI library resolvers
- Generates TypeScript declarations
- Handles `default` export for third-party UI libraries
## Supported UI Libraries
Built-in resolvers for:
| Library | Import |
|---------|--------|
| Ano UI | `AnoUIResolver()` |
| uni-ui | `UniUIResolver()` |
| wot-design-uni | `WotDesignUniResolver()` |
| uv-uni | `UvUniResolver()` |
| uview-pro | `UviewProResolver()` |
| z-paging | `ZPagingResolver()` |
## TypeScript Declarations
For pnpm users, create `.npmrc`:
```ini
shamefully-hoist = true
```
Generated `components.d.ts` example:
```ts
declare module 'vue' {
export interface GlobalComponents {
AButton: typeof import('ano-ui/components/AButton/AButton.vue')['default']
UniCalendar: typeof import('@dcloudio/uni-ui/lib/uni-calendar/uni-calendar.vue')['default']
MyComponent: typeof import('./src/components/MyComponent.vue')['default']
}
}
```
## Third-Party Component Handling
For third-party components like `@dcloudio/uni-ui` and `ano-ui`, the plugin automatically adds the `default` property to handle H5 compatibility issues:
```diff
declare module 'vue' {
export interface GlobalComponents {
- AButton: typeof import('ano-ui/components/AButton/AButton.vue')['AButton']
+ AButton: typeof import('ano-ui/components/AButton/AButton.vue')['default']
}
}
```
## Full Configuration
See [unplugin-vue-components documentation](https://github.com/antfu/unplugin-vue-components) for all options.
<!--
Source references:
- https://github.com/uni-helper/vite-plugin-uni-components
- https://uni-helper.js.org/vite-plugin-uni-components
-->

View File

@@ -0,0 +1,143 @@
---
name: vite-plugin-uni-layouts
description: Nuxt-like layouts system for Vite-powered uni-app projects
---
# vite-plugin-uni-layouts
Provides a Nuxt-like layout system for uni-app. Wraps pages with reusable layout components.
## Installation
```bash
npm i -D @uni-helper/vite-plugin-uni-layouts
```
## Setup
```ts
// vite.config.ts
import uni from '@dcloudio/vite-plugin-uni'
import UniLayouts from '@uni-helper/vite-plugin-uni-layouts'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [UniLayouts(), uni()],
})
```
## Creating Layouts
Create layout files in `src/layouts/` directory:
```vue
<!-- src/layouts/default.vue -->
<template>
<view class="layout">
<slot name="header" />
<slot>main content</slot>
<slot name="footer" />
</view>
</template>
```
## Applying Layouts
### Via pages.json (traditional)
```json
{
"pages": [{
"path": "pages/index/index",
"layout": "default"
},
{
"path": "pages/about/index",
"layout": false // Disable layout
}]
}
```
### Via definePage (recommended)
```vue
<script setup>
definePage({
layout: 'default',
})
</script>
```
## Dynamic Layouts
Use the `<uni-layout>` component for dynamic layout switching:
```vue
<script setup>
const layoutName = ref('default')
</script>
<template>
<!-- Disable page layout first -->
<uni-layout :name="layoutName">
<template #header>
<text>Header content</text>
</template>
Main content here
<template #footer>
<text>Footer content</text>
</template>
</uni-layout>
</template>
```
### Accessing Layout Ref
```vue
<script setup>
const uniLayout = ref()
onMounted(() => {
console.log(uniLayout.value) // Access layout component
})
</script>
<template>
<uni-layout ref="uniLayout">
Content
</uni-layout>
</template>
```
Options API:
```vue
<script>
export default {
onLoad() {
console.log(this.$refs.uniLayout)
},
}
</script>
```
## How It Works
The plugin does two things:
1. Auto-scans and globally registers components from `layouts/` directory
2. Wraps pages with the specified layout component
> **Note:** WeChat Mini Program limitation - If using `web-view` component, layout wrapping may not work properly.
## Configuration
See [type definitions](https://github.com/uni-helper/vite-plugin-uni-layouts/blob/main/src/types.ts) for all options.
<!--
Source references:
- https://github.com/uni-helper/vite-plugin-uni-layouts
- https://uni-helper.js.org/vite-plugin-uni-layouts
-->

View File

@@ -0,0 +1,103 @@
---
name: vite-plugin-uni-manifest
description: Write uni-app manifest.json in TypeScript with type safety and IntelliSense
---
# vite-plugin-uni-manifest
Write your uni-app `manifest.json` configuration in TypeScript with full type safety and IntelliSense support.
## Installation
```bash
npm i -D @uni-helper/vite-plugin-uni-manifest
```
## Setup
```ts
// vite.config.ts
import Uni from '@dcloudio/vite-plugin-uni'
import UniManifest from '@uni-helper/vite-plugin-uni-manifest'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [UniManifest(), Uni()],
})
```
## Configuration File
Create `manifest.config.ts` (or .js/.json):
```ts
// manifest.config.ts
import { defineManifestConfig } from '@uni-helper/vite-plugin-uni-manifest'
export default defineManifestConfig({
name: 'my-uni-app',
appid: '__UNI__XXXXXXX',
description: 'My awesome uni-app project',
versionName: '1.0.0',
versionCode: '100',
transformPx: false,
app: {
// App-specific config
},
mp-weixin: {
// WeChat Mini Program config
},
mp-alipay: {
// Alipay Mini Program config
},
h5: {
// H5 config
},
})
```
## Benefits
- **Type Safety**: Full TypeScript intellisense for all manifest properties
- **Code Reuse**: Import and reuse configuration values
- **Comments**: Add comments to explain configuration choices
- **Environment-based Config**: Use conditionals for different environments
## Example with Dynamic Config
```ts
import { defineManifestConfig } from '@uni-helper/vite-plugin-uni-manifest'
import { version } from './package.json'
export default defineManifestConfig({
name: 'My App',
versionName: version,
versionCode: version.replace(/\./g, ''),
// Platform-specific config
'mp-weixin': {
appid: process.env.WX_APPID || '',
setting: {
es6: true,
enhance: true,
},
},
h5: {
title: 'My H5 App',
router: {
mode: 'hash',
},
},
})
```
## Configuration Options
See [types.ts](https://github.com/uni-helper/vite-plugin-uni-manifest/tree/main/packages/core/src/types.ts) for all available options.
<!--
Source references:
- https://github.com/uni-helper/vite-plugin-uni-manifest
- https://uni-helper.js.org/vite-plugin-uni-manifest
-->

View File

@@ -0,0 +1,181 @@
---
name: vite-plugin-uni-middleware
description: Route middleware support for uni-app - implement guards, auth, and page lifecycle hooks
---
# vite-plugin-uni-middleware
Add Express-style middleware support to uni-app routing. Implement authentication guards, page analytics, and custom route logic.
## Installation
```bash
npm i -D @uni-helper/vite-plugin-uni-middleware
```
## Setup
```ts
// vite.config.ts
import Uni from '@dcloudio/vite-plugin-uni'
import UniMiddleware from '@uni-helper/vite-plugin-uni-middleware'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [UniMiddleware(), Uni()],
})
```
## Creating Middleware
Create middleware files in `src/middleware/` directory:
```ts
// src/middleware/auth.ts
import { defineMiddleware } from '@uni-helper/vite-plugin-middleware'
export default defineMiddleware((to, from, next) => {
const token = uni.getStorageSync('token')
if (!token && to.path !== '/pages/login/index') {
// Redirect to login
next('/pages/login/index')
} else {
// Continue navigation
next()
}
})
```
```ts
// src/middleware/analytics.ts
export default defineMiddleware((to, from, next) => {
// Track page view
uni.report('page_view', {
path: to.path,
from: from.path,
timestamp: Date.now(),
})
next()
})
```
```ts
// src/middleware/logger.ts
export default defineMiddleware((to, from, next) => {
console.log(`[Router] ${from.path} -> ${to.path}`)
next()
})
```
## Applying Middleware
### Via definePage (recommended)
```vue
<script setup>
definePage({
middlewares: ['auth', 'analytics'],
})
</script>
```
### Via pages.json
```json
{
"pages": [{
"path": "pages/profile/index",
"middlewares": ["auth"]
}]
}
```
### Global Middleware
Create `src/middleware/index.ts` for global middleware:
```ts
// src/middleware/index.ts
export default defineMiddleware((to, from, next) => {
// Runs on every navigation
console.log('Global middleware')
next()
})
```
## Middleware Context
```ts
interface MiddlewareContext {
to: {
path: string
query: Record<string, string>
meta?: Record<string, any>
}
from: {
path: string
query: Record<string, string>
}
next: (path?: string) => void
}
```
## Middleware Order
Middleware executes in declaration order:
```vue
<script setup>
definePage({
// Runs: logger -> auth -> analytics
middlewares: ['logger', 'auth', 'analytics'],
})
</script>
```
## Navigation Control
```ts
export default defineMiddleware((to, from, next) => {
// Continue to route
next()
// Redirect to different route
next('/pages/other/index')
// Redirect with query
next({
path: '/pages/login/index',
query: { redirect: to.path },
})
// Cancel navigation (stay on current page)
next(false)
})
```
## Async Middleware
```ts
export default defineMiddleware(async (to, from, next) => {
try {
const user = await fetchUserInfo()
if (user.isBanned) {
next('/pages/banned/index')
} else {
next()
}
} catch (error) {
next('/pages/error/index')
}
})
```
<!--
Source references:
- https://github.com/uni-helper/vite-plugin-uni-middleware
- https://uni-helper.js.org/vite-plugin-uni-middleware
-->

View File

@@ -0,0 +1,186 @@
---
name: vite-plugin-uni-pages
description: File-based routing system for Vite-powered uni-app projects with automatic page discovery and TypeScript support
---
# vite-plugin-uni-pages
Provides file-based routing for uni-app projects using Vite. Automatically generates `pages.json` configuration from your file structure.
## Installation
```bash
npm i -D @uni-helper/vite-plugin-uni-pages
```
## Basic Setup
```ts
// vite.config.ts
import Uni from '@dcloudio/vite-plugin-uni'
import UniPages from '@uni-helper/vite-plugin-uni-pages'
import { defineConfig } from 'vite'
// Place UniPages before Uni
export default defineConfig({
plugins: [UniPages(), Uni()],
})
```
## TypeScript Support
Add types to `tsconfig.json`:
```json
{
"compilerOptions": {
"types": ["@uni-helper/vite-plugin-uni-pages"]
}
}
```
## Global Configuration
Create `pages.config.ts` (or .js/.json) for global settings:
```ts
// pages.config.ts
import { defineUniPages } from '@uni-helper/vite-plugin-uni-pages'
export default defineUniPages({
// Optional: manual pages have highest priority
pages: [],
globalStyle: {
navigationBarTextStyle: 'black',
navigationBarTitleText: '@uni-helper',
},
})
```
## Virtual Module
Access page metadata via virtual module:
```ts
/// <reference types="@uni-helper/vite-plugin-uni-pages/client" />
import { pages } from 'virtual:uni-pages'
console.log(pages)
```
## definePage Macro
Define page configuration directly in SFC files:
```vue
<script setup lang="ts">
// Object form
definePage({
style: {
navigationBarTitleText: 'hello world',
},
middlewares: ['auth'],
})
// Function form (supports TypeScript, async)
definePage(() => {
return {
style: {
navigationBarTitleText: 'dynamic title',
},
}
})
// Async form
definePage(async () => {
const title = await fetchTitle()
return {
style: { navigationBarTitleText: title },
}
})
</script>
```
### Important Notes for definePage
- Write inside `<script>` block
- `definePage` runs in a different scope than SFC (no access to SFC variables)
- Page path is auto-generated from file path
- Only one `definePage` per file
- Supports importing external libraries (pure JS only)
- Supports TypeScript type imports (types are stripped)
### Using with Condition Compile
```vue
<script setup>
import { isH5 } from '@uni-helper/uni-env'
definePage(() => {
const title = isH5 ? 'H5 Environment' : 'Other Platform'
return {
style: { navigationBarTitleText: title },
}
})
</script>
```
## Configuration Options
```ts
export interface Options {
/** Generate TypeScript declarations */
dts?: boolean | string // default: true (outputs uni-pages.d.ts)
/** Config file pattern */
configSource: string // default: 'pages.config.(ts|mts|cts|js|cjs|mjs|json)'
/** Default home page */
homePage: string // default: 'pages/index' or 'pages/index/index'
/** Merge with existing pages.json */
mergePages: boolean // default: true
/** Pages directory */
dir: string // default: 'src/pages'
/** Sub-packages directories */
subPackages: string[] // e.g., ['src/pages-sub']
/** Output directory for pages.json */
outDir: string // default: 'src'
/** Exclude patterns */
exclude: string[] // default: []
/** Route block language in SFC */
routeBlockLang: 'json5' | 'jsonc' | 'json' | 'yaml' | 'yml' // default: 'json5'
// Lifecycle hooks
onBeforeLoadUserConfig?: (ctx: PageContext) => void
onAfterLoadUserConfig?: (ctx: PageContext) => void
onBeforeScanPages?: (ctx: PageContext) => void
onAfterScanPages?: (ctx: PageContext) => void
onBeforeMergePageMetaData?: (ctx: PageContext) => void
onAfterMergePageMetaData?: (ctx: PageContext) => void
onBeforeWriteFile?: (ctx: PageContext) => void
onAfterWriteFile?: (ctx: PageContext) => void
}
```
## Usage with Layouts
```vue
<script setup>
definePage({
layout: 'default', // Specify layout
middlewares: ['auth'],
})
</script>
```
<!--
Source references:
- https://github.com/uni-helper/vite-plugin-uni-pages
- https://uni-helper.js.org/vite-plugin-uni-pages
-->

View File

@@ -0,0 +1,119 @@
---
name: vite-plugin-uni-platform-modifier
description: Platform modifiers for attributes and directives in uni-app - optimize bundle size by removing unused platform code
---
# vite-plugin-uni-platform-modifier
Add platform modifiers to attributes and directives for conditional compilation at the template level. Reduces bundle size by removing code for other platforms.
## Installation
```bash
npm i -D @uni-helper/vite-plugin-uni-platform-modifier
```
## Setup
```ts
// vite.config.ts
import Uni from '@dcloudio/vite-plugin-uni'
import UniPlatformModifier from '@uni-helper/vite-plugin-uni-platform-modifier'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [UniPlatformModifier(), Uni()],
})
```
## Platform Modifiers
### Directive Modifiers
```vue
<template>
<!-- Only render on H5 -->
<view v-if.h5="condition">H5 only content</view>
<!-- Only render on WeChat -->
<button v-if.mp-weixin="true">WeChat specific</button>
<!-- Only render on App -->
<native-view v-if.app="true">Native view</native-view>
<!-- Platform-specific event -->
<view @click.h5="handleH5Click" @click.mp-weixin="handleWeChatClick">
Platform-specific click
</view>
</template>
```
### Attribute Modifiers
```vue
<template>
<!-- Different classes per platform -->
<view class.h5="h5-container" class.mp-weixin="wechat-container">
Content
</view>
<!-- Platform-specific styles -->
<view :style.h5="{ padding: '20px' }" :style.app="{ padding: '10px' }">
Styled content
</view>
</template>
```
## Supported Platforms
| Modifier | Platform |
|----------|----------|
| `.h5` | H5/Web |
| `.mp-weixin` | WeChat Mini Program |
| `.mp-alipay` | Alipay Mini Program |
| `.mp-baidu` | Baidu Smart Program |
| `.mp-toutiao` | Douyin Mini Program |
| `.mp-qq` | QQ Mini Program |
| `.app` | iOS/Android App |
## How It Works
The plugin transforms templates at build time:
```vue
<!-- Source -->
<view v-if.h5="show">H5 Only</view>
<!-- Transformed for H5 build -->
<view v-if="show">H5 Only</view>
<!-- Removed for non-H5 builds -->
```
## Use Cases
- Platform-specific UI components
- Different interactions per platform
- Platform-optimized styles
- Conditional event handlers
## Combining with Other Plugins
```ts
// vite.config.ts
export default defineConfig({
plugins: [
UniComponents(),
UniPages(),
UniPlatform(), // File-based platform
UniPlatformModifier(), // Directive/attribute modifiers
Uni(),
],
})
```
<!--
Source references:
- https://github.com/uni-helper/vite-plugin-uni-platform-modifier
- https://uni-helper.js.org/vite-plugin-uni-platform-modifier
-->

View File

@@ -0,0 +1,105 @@
---
name: vite-plugin-uni-platform
description: File-based platform compilation for uni-app - compile different files based on target platform
---
# vite-plugin-uni-platform
Compile different files based on target platform using file naming conventions. Supports platform-specific implementations without conditional compilation.
## Installation
```bash
npm i -D @uni-helper/vite-plugin-uni-platform
```
## Setup
```ts
// vite.config.ts
import Uni from '@dcloudio/vite-plugin-uni'
import UniPlatform from '@uni-helper/vite-plugin-uni-platform'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [UniPlatform(), Uni()],
})
```
## File Naming Convention
Use platform suffixes in filenames:
```
src/
utils/
request.ts # Default implementation
request.h5.ts # H5-specific
request.mp-weixin.ts # WeChat Mini Program
request.app.ts # App (iOS/Android)
```
## Supported Platforms
| Suffix | Platform |
|--------|----------|
| `.h5.ts` | H5/Web |
| `.mp-weixin.ts` | WeChat Mini Program |
| `.mp-alipay.ts` | Alipay Mini Program |
| `.mp-baidu.ts` | Baidu Smart Program |
| `.mp-toutiao.ts` | Douyin Mini Program |
| `.mp-qq.ts` | QQ Mini Program |
| `.mp-kuaishou.ts` | Kuaishou Mini Program |
| `.app.ts` | iOS/Android App |
| `.app-plus.ts` | App (alternative) |
| `.harmony` | HarmonyOS |
## Import Usage
Import without the platform suffix:
```ts
// This automatically resolves to the correct platform version
import { request } from './utils/request'
```
## Example
```ts
// utils/request.ts - Default implementation
export const request = (options: RequestOptions) => {
return uni.request(options)
}
// utils/request.h5.ts - H5 with axios
import axios from 'axios'
export const request = (options: RequestOptions) => {
return axios.request(options)
}
// utils/request.mp-weixin.ts - WeChat specific
export const request = (options: RequestOptions) => {
// Add WeChat-specific headers
return uni.request({
...options,
header: {
...options.header,
'X-Platform': 'weixin',
},
})
}
```
## Benefits
- Cleaner code without `#ifdef` conditions
- Type-safe platform implementations
- Tree-shaking removes unused platform code
- Better IDE support and navigation
<!--
Source references:
- https://github.com/uni-helper/vite-plugin-uni-platform
- https://uni-helper.js.org/vite-plugin-uni-platform
-->

View File

@@ -0,0 +1,153 @@
---
name: create-uni
description: CLI scaffolding tool for creating uni-app projects with best practices
---
# create-uni
Interactive CLI tool for scaffolding uni-app projects. Quickly create projects with your choice of templates, plugins, and UI libraries.
## Usage
```bash
# Create new project
npm create uni@latest
# With project name
npm create uni@latest my-project
# With options
npm create uni@latest my-project --ts --template vitesse -m pinia -u wot
```
## CLI Options
| Option | Shorthand | Description |
|--------|-----------|-------------|
| `--template` | `-t` | Select project template |
| `--typescript` | `--ts` | Enable TypeScript |
| `--eslint` | `-e` | Add ESLint |
| `--plugin` | `-p` | Add Vite plugins |
| `--module` | `-m` | Add functional modules |
| `--ui` | `-u` | Add UI component library |
| `--gui` | - | Launch GUI interface |
| `--info` | - | Show project info |
## Templates
| Template | Description | Value |
|----------|-------------|-------|
| Vitesse Uni App | Vite + uni-app starter with best practices | `vitesse` |
| Wot Starter | Based on vitesse with wot-ui | `wot-starter` |
| Wot Starter Retail | Retail/e-commerce template | `wot-starter-retail` |
| Unisave | Web-first uni-app development | `unisave` |
| TMUI 3.2 | Enterprise component library | `tmui32` |
| uView Pro Starter | uView Pro quick start | `uview-pro-starter` |
| uView Pro Demo | uView Pro full demo | `uview-pro-demo` |
## Available Plugins
| Plugin | CLI Value | Description |
|--------|-----------|-------------|
| vite-plugin-uni-components | `import` | Auto component import |
| vite-plugin-uni-pages | `pages` | File-based routing |
| vite-plugin-uni-layouts | `layouts` | Nuxt-like layouts |
| vite-plugin-uni-manifest | `manifest` | TypeScript manifest |
| vite-plugin-uni-platform | `filePlatform` | Platform-specific files |
| vite-plugin-uni-platform-modifier | `platformModifier` | Platform modifiers |
| vite-plugin-uni-middleware | `middleware` | Route middleware |
| uni-ku-root | `root` | Virtual root component |
## Available Modules
| Module | CLI Value | Description |
|--------|-----------|-------------|
| Pinia | `pinia` | State management |
| UnoCSS | `unocss` | Atomic CSS |
| uni-network | `uniNetwork` | HTTP client |
| uni-use | `uniUse` | Composable utilities |
| uni-promises | `uniPromises` | Promise wrappers |
| Uni ECharts | `uniEcharts` | Chart component |
| z-paging | `zPaging` | Pagination component |
## UI Libraries
| UI Library | CLI Value | Description |
|------------|-----------|-------------|
| Uni UI | `uni` | Official DCloud UI |
| Wot Design Uni | `wot` | Lightweight, beautiful |
| uView Pro | `uview-pro` | Vue 3 + TypeScript |
| NutUI Uniapp | `nut` | JD style, e-commerce |
| Skiyee UI | `skiyee` | Unique design language |
| UV UI | `uv` | Multi-platform |
| Ano UI | `ano` | UnoCSS-based |
## Examples
### Basic TypeScript Project
```bash
npm create uni@latest my-app --ts
```
### With Vitesse Template
```bash
npm create uni@latest my-app --ts --template vitesse
```
### Full-Featured Setup
```bash
npm create uni@latest my-app \
--ts \
--template vitesse \
-p pages -p layouts -p import \
-m pinia -m unocss -m uniUse \
-u wot \
-e
```
### GUI Mode
```bash
npm create uni@latest --gui
```
## Project Structure
Created projects follow this structure:
```
my-project/
├── src/
│ ├── components/ # Vue components
│ ├── composables/ # Composable functions
│ ├── layouts/ # Layout components (if layouts plugin)
│ ├── pages/ # Page components
│ ├── static/ # Static assets
│ ├── stores/ # Pinia stores (if pinia)
│ ├── App.vue
│ ├── main.ts
│ ├── manifest.config.ts # (if manifest plugin)
│ └── pages.config.ts # (if pages plugin)
├── index.html
├── package.json
├── tsconfig.json
├── vite.config.ts
└── uno.config.ts # (if unocss)
```
## Post-Creation
```bash
cd my-project
npm install
npm run dev
```
<!--
Source references:
- https://github.com/uni-helper/create-uni
- https://uni-helper.js.org/create-uni
-->

View File

@@ -0,0 +1,263 @@
---
name: vitesse-uni-app
description: Vite-powered opinionated uni-app starter template with best practices
---
# vitesse-uni-app
Opinionated uni-app starter template powered by Vite. Includes best practices, pre-configured tooling, and modern development experience.
## Features
- ⚡️ **Vite** - Fast development and building
- 🌍 **uni-app** - Cross-platform development
- 🖖 **Vue 3** - Composition API, `<script setup>`
- 🔷 **TypeScript** - Type safety
- 🎨 **UnoCSS** - Atomic CSS
- 📦 **Auto Import** - Components and composables
- 🗂 **File-based Routing** - vite-plugin-uni-pages
- 📐 **Layout System** - Nuxt-like layouts
- 🔧 **ESLint** - Code linting
## Quick Start
```bash
# Create with create-uni
npm create uni@latest my-app --template vitesse
# Or clone directly
git clone https://github.com/uni-helper/vitesse-uni-app.git my-app
```
## Project Structure
```
vitesse-uni-app/
├── src/
│ ├── components/ # Auto-imported components
│ ├── composables/ # Auto-imported composables
│ ├── layouts/ # Layout components
│ │ ├── default.vue
│ │ └── home.vue
│ ├── pages/ # File-based routing
│ │ ├── index.vue
│ │ └── about/
│ │ └── index.vue
│ ├── static/ # Static assets
│ ├── stores/ # Pinia stores
│ ├── styles/ # Global styles
│ ├── App.vue
│ ├── main.ts
│ ├── manifest.config.ts # TypeScript manifest
│ └── pages.config.ts # Global pages config
├── types/ # Type definitions
├── index.html
├── package.json
├── tsconfig.json
├── vite.config.ts
├── uno.config.ts
└── eslint.config.js
```
## Pre-configured Plugins
The template includes these pre-configured plugins:
```ts
// vite.config.ts
export default defineConfig({
plugins: [
UniComponents({
resolvers: [AnoUIResolver()],
}),
UniPages(),
UniLayouts(),
UniManifest(),
Uni(),
],
})
```
## Auto Imports
### Components
Components in `src/components/` are auto-imported:
```vue
<template>
<!-- No import needed -->
<MyButton />
</template>
```
### Composables
Files in `src/composables/` are auto-imported:
```ts
// src/composables/useCounter.ts
export function useCounter() {
const count = ref(0)
const inc = () => count.value++
return { count, inc }
}
```
```vue
<script setup>
// No import needed
const { count, inc } = useCounter()
</script>
```
### Vue APIs
Vue APIs are auto-imported:
```vue
<script setup>
// No need to import ref, computed, etc.
const count = ref(0)
const doubled = computed(() => count.value * 2)
</script>
```
## Routing
File-based routing with pages in `src/pages/`:
```
pages/
├── index.vue # /pages/index/index
├── about.vue # /pages/about/index
└── user/
├── index.vue # /pages/user/index
└── [id].vue # /pages/user/:id
```
### Page Configuration
```vue
<script setup>
definePage({
style: {
navigationBarTitleText: 'About',
},
layout: 'default',
})
</script>
```
## Layouts
Create layouts in `src/layouts/`:
```vue
<!-- src/layouts/default.vue -->
<template>
<view class="layout">
<slot name="header" />
<slot />
<slot name="footer" />
</view>
</template>
```
Apply in pages:
```vue
<script setup>
definePage({
layout: 'default',
})
</script>
<template>
<template #header>
<NavBar />
</template>
<div>Content</div>
</template>
```
## Styling with UnoCSS
```vue
<template>
<view class="p-32 bg-gray-100">
<text class="text-32 font-bold text-primary">
Styled with UnoCSS
</text>
</view>
</template>
```
## State Management with Pinia
```ts
// src/stores/user.ts
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', () => {
const name = ref('')
const isLoggedIn = computed(() => !!name.value)
function login(userName: string) {
name.value = userName
}
return { name, isLoggedIn, login }
})
```
```vue
<script setup>
const user = useUserStore()
</script>
```
## Data Fetching
```vue
<script setup>
const { data: users, pending, error } = useFetch('/api/users')
</script>
<template>
<view v-if="pending">Loading...</view>
<view v-else-if="error">Error: {{ error.message }}</view>
<view v-else>
<view v-for="user in users" :key="user.id">
{{ user.name }}
</view>
</view>
</template>
```
## Deployment
### Build for production
```bash
npm run build
```
### Platform-specific builds
```bash
# H5
npm run build:h5
# WeChat Mini Program
npm run build:mp-weixin
# App
npm run build:app
```
<!--
Source references:
- https://github.com/uni-helper/vitesse-uni-app
- https://uni-helper.js.org/vitesse-uni-app
-->

View File

@@ -0,0 +1,155 @@
---
name: uni-env
description: Environment detection utilities for uni-app - detect platform at runtime
---
# uni-env
Runtime environment detection utilities for uni-app. Detect the current platform in a type-safe way.
## Installation
```bash
npm i @uni-helper/uni-env
```
## Usage
```ts
import { isH5, isMpWeixin, isApp, isMp } from '@uni-helper/uni-env'
if (isH5) {
console.log('Running in H5')
}
if (isMpWeixin) {
console.log('Running in WeChat Mini Program')
}
```
## Available Detectors
### Platform Groups
| Detector | Description |
|----------|-------------|
| `isH5` | H5/Web platform |
| `isApp` | iOS/Android App |
| `isMp` | Any Mini Program |
| `isQuickapp` | Quick App |
### Mini Program Detectors
| Detector | Description |
|----------|-------------|
| `isMpWeixin` | WeChat Mini Program |
| `isMpAlipay` | Alipay Mini Program |
| `isMpBaidu` | Baidu Smart Program |
| `isMpToutiao` | Douyin Mini Program |
| `isMpQQ` | QQ Mini Program |
| `isMpKuaishou` | Kuaishou Mini Program |
| `isMpJd` | JD Mini Program |
| `isMpHarmony` | HarmonyOS Meta Service |
| `isMpLark` | Feishu/Lark Mini Program |
### Development Detectors
| Detector | Description |
|----------|-------------|
| `isDev` | Development environment |
| `isProd` | Production environment |
## Use Cases
### Conditional Logic
```ts
import { isH5, isMpWeixin, isApp } from '@uni-helper/uni-env'
function getStorageAdapter() {
if (isH5) {
return new LocalStorageAdapter()
}
if (isMpWeixin) {
return new WechatStorageAdapter()
}
if (isApp) {
return new NativeStorageAdapter()
}
return new UniStorageAdapter()
}
```
### Platform-Specific Features
```ts
import { isH5, isMpWeixin } from '@uni-helper/uni-env'
function share(content: ShareContent) {
if (isMpWeixin) {
// Use WeChat share API
wx.showShareMenu({ withShareTicket: true })
} else if (isH5) {
// Use Web Share API
navigator.share({
title: content.title,
url: content.url,
})
} else {
// Use uni-app generic share
uni.share({
title: content.title,
path: content.path,
})
}
}
```
### With definePage
```ts
import { isH5 } from '@uni-helper/uni-env'
definePage(() => {
const title = isH5 ? 'H5 Version' : 'Mobile Version'
return {
style: {
navigationBarTitleText: title,
},
}
})
```
## Important Note
This package is primarily for **plugin developers**. For runtime conditional compilation, use uni-app's [official conditional compilation](https://uniapp.dcloud.net.cn/tutorial/platform.html#preprocessor) with `/* #ifdef */` comments.
For better conditional compilation support, consider using [unplugin-preprocessor-directives](https://github.com/KeJunMao/unplugin-preprocessor-directives).
## Comparison with Conditional Compilation
```ts
// Runtime detection (uni-env)
import { isH5 } from '@uni-helper/uni-env'
if (isH5) {
// This code exists in all builds
doH5Thing()
}
// Build-time conditional compilation
// #ifdef H5
doH5Thing()
// #endif
// This code only exists in H5 builds
```
Choose based on your needs:
- Use **uni-env** for runtime detection when you need the same bundle for multiple platforms
- Use **conditional compilation** for build-time optimization and smaller bundles
<!--
Source references:
- https://github.com/uni-helper/uni-env
- https://uni-helper.js.org/uni-env
-->

View File

@@ -0,0 +1,175 @@
---
name: unocss-preset-uni
description: UnoCSS preset for uni-app with platform-specific utilities and rpx support
---
# unocss-preset-uni
UnoCSS preset designed for uni-app development. Provides utilities for rpx units and platform-specific styling.
## Installation
```bash
npm i -D @uni-helper/unocss-preset-uni
```
## Setup
```ts
// uno.config.ts
import { defineConfig } from 'unocss'
import { presetUni } from '@uni-helper/unocss-preset-uni'
export default defineConfig({
presets: [
presetUni(),
],
})
```
## Features
- **rpx support**: Automatic conversion to rpx units
- **Platform variants**: Style targeting specific platforms
- **Safe area utilities**: Handle notches and safe areas
- **Compatible with**: Mini programs, H5, and App
## RPX Utilities
The preset automatically converts pixel values to rpx:
```html
<!-- These generate rpx units -->
<view class="w-100"></view> <!-- width: 100rpx -->
<view class="h-50"></view> <!-- height: 50rpx -->
<view class="m-20"></view> <!-- margin: 20rpx -->
<view class="p-16"></view> <!-- padding: 16rpx -->
<view class="text-32"></view> <!-- font-size: 32rpx -->
```
## Platform Variants
Apply styles to specific platforms:
```html
<!-- Only apply on H5 -->
<view class="h5:bg-red"></view>
<!-- Only apply on WeChat -->
<view class="mp-weixin:bg-blue"></view>
<!-- Only apply on App -->
<view class="app:bg-green"></view>
<!-- Combine with responsive -->
<view class="h5:p-20 mp-weixin:p-10"></view>
```
## Safe Area Utilities
```html
<!-- Safe area padding -->
<view class="pt-safe"></view> <!-- padding-top: env(safe-area-inset-top) -->
<view class="pb-safe"></view> <!-- padding-bottom: env(safe-area-inset-bottom) -->
<view class="px-safe"></view> <!-- padding-x with safe area -->
<!-- Safe area margin -->
<view class="mt-safe"></view>
<view class="mb-safe"></view>
<!-- Full safe area -->
<view class="safe-area"></view>
```
## Tab Bar Utilities
```html
<!-- Padding for tab bar -->
<view class="pb-tabbar"></view>
<!-- Margin for tab bar -->
<view class="mb-tabbar"></view>
```
## Status Bar Utilities
```html
<!-- Status bar height -->
<view class="h-statusbar"></view>
<view class="pt-statusbar"></view>
```
## Configuration
```ts
// uno.config.ts
import { defineConfig } from 'unocss'
import { presetUni } from '@uni-helper/unocss-preset-uni'
export default defineConfig({
presets: [
presetUni({
// rpx base width (default: 750)
baseWidth: 750,
// Enable platform variants
platform: true,
// Enable safe area utilities
safeArea: true,
// Custom platforms
platforms: ['mp-weixin', 'mp-alipay', 'h5', 'app'],
}),
],
})
```
## With Vite
```ts
// vite.config.ts
import Uni from '@dcloudio/vite-plugin-uni'
import UnoCSS from 'unocss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
UnoCSS(),
Uni(),
],
})
```
## Example
```vue
<template>
<view class="page bg-gray-100">
<!-- Status bar spacing -->
<view class="h-statusbar"></view>
<!-- Header with safe area -->
<view class="px-32 pt-safe flex items-center justify-between">
<text class="text-36 font-bold">Title</text>
</view>
<!-- Content -->
<view class="p-32 flex flex-col gap-20">
<!-- Platform-specific styling -->
<view class="card h5:shadow-lg mp-weixin:border">
<text class="text-28 text-gray-800">Content</text>
</view>
</view>
<!-- Bottom safe area for devices with notches -->
<view class="pb-safe"></view>
</view>
</template>
```
<!--
Source references:
- https://github.com/uni-helper/unocss-preset-uni
- https://uni-helper.js.org/unocss-preset-uni
-->