H5端API库,为Taro跨端开发框架提供Web/H5端的API实现
—
Essential framework utilities including the main Taro object, app lifecycle management, and system utilities that form the foundation of Taro H5 applications.
The central Taro object provides core utilities for pixel transformation, environment detection, and application information.
/**
* Main Taro object exported as default from @tarojs/taro-h5
* Contains core utilities and framework integration
*/
interface TaroCore {
// Pixel transformation utilities
pxTransform(size: number): string;
initPxTransform(config: PxTransformConfig): void;
// Application information
getAppInfo(): AppInfo;
canIUseWebp(): boolean;
// Environment and framework integration
getEnv(): string;
getCurrentInstance(): ComponentInstance;
getApp<T>(): T;
getCurrentPages(): PageInstance[];
// Event system
eventCenter: EventCenter;
Events: typeof Events;
// Framework utilities
nextTick(callback: Function): void;
options: Record<string, any>;
history: History;
// Interceptor system
interceptors: Interceptors;
interceptorify: (fn: Function) => Function;
// Component behavior system
Behavior: (behavior: any) => any;
// Current context
Current: CurrentContext;
// Preload functionality
preload: (data: any) => void;
// Constants
ENV_TYPE: typeof ENV_TYPE;
Link: any;
// Plugin system (not supported in H5)
requirePlugin(name: string): never;
}Usage Examples:
import Taro from "@tarojs/taro-h5";
// Initialize pixel transformation
Taro.initPxTransform({
designWidth: 750,
deviceRatio: {
640: 1.17,
750: 1,
828: 0.905
}
});
// Transform pixels
const transformedSize = Taro.pxTransform(100); // Returns "1rem" or similar
// Get app information
const appInfo = Taro.getAppInfo();
console.log(`Platform: ${appInfo.platform}, Version: ${appInfo.taroVersion}`);
// Check WebP support
if (Taro.canIUseWebp()) {
console.log('WebP images are supported');
}
// Get environment
const env = Taro.getEnv();
console.log(`Running in: ${env}`); // 'WEB' for H5
// Get current component instance
const instance = Taro.getCurrentInstance();
console.log(instance.router?.params);Utilities for converting design pixels to responsive units based on device characteristics.
/**
* Initialize pixel transformation configuration
* @param config - Configuration options for pixel transformation
*/
function initPxTransform(config: PxTransformConfig): void;
/**
* Transform pixels using configured settings
* @param size - Pixel size to transform
* @returns Transformed size string with unit
*/
function pxTransform(size: number): string;
interface PxTransformConfig {
/** Design width in pixels (default: 750) */
designWidth?: number;
/** Device ratio mapping (default: {640: 1.17, 750: 1, 828: 0.905}) */
deviceRatio?: Record<number, number>;
/** Base font size for rem calculations (default: 20) */
baseFontSize?: number;
/** Decimal precision for transformed values (default: 5) */
unitPrecision?: number;
/** Target unit for transformation (default: 'rem') */
targetUnit?: 'rem' | 'px' | 'vw';
}Utilities for retrieving application and environment information.
/**
* Get comprehensive application information
* @returns Object containing platform and version details
*/
function getAppInfo(): AppInfo;
/**
* Check if WebP image format is supported in current browser
* @returns true if WebP is supported, false otherwise
*/
function canIUseWebp(): boolean;
interface AppInfo {
/** Platform identifier (always 'WEB' for H5) */
platform: string;
/** Taro framework version string */
taroVersion: string;
/** Current design width setting */
designWidth: number;
}Core framework integration utilities for component and page management.
/**
* Get current component instance with context information
* @returns Current component instance or undefined
*/
function getCurrentInstance(): ComponentInstance | undefined;
/**
* Get the current app instance
* @returns App instance with type information
*/
function getApp<T = any>(): T;
/**
* Get current page stack
* @returns Array of page instances in navigation order
*/
function getCurrentPages(): PageInstance[];
/**
* Get current environment type
* @returns Environment identifier string
*/
function getEnv(): string;
/**
* Schedule callback for next tick
* @param callback - Function to execute on next tick
*/
function nextTick(callback: Function): void;
interface ComponentInstance {
/** Associated page context */
page?: any;
/** Router information */
router?: {
params: Record<string, string>;
path: string;
};
/** Component scope */
scope?: any;
/** Additional component properties */
[key: string]: any;
}
interface PageInstance {
/** Page route path */
route: string;
/** Page query parameters */
options: Record<string, string>;
/** Additional page properties */
[key: string]: any;
}Centralized event management system for cross-component communication.
/**
* Global event center for pub/sub communication
*/
interface EventCenter {
on(event: string, callback: Function): void;
off(event: string, callback?: Function): void;
trigger(event: string, ...args: any[]): void;
once(event: string, callback: Function): void;
}
/**
* Events class for creating event instances
*/
class Events {
on(event: string, callback: Function): void;
off(event: string, callback?: Function): void;
trigger(event: string, ...args: any[]): void;
once(event: string, callback: Function): void;
}Request and function interceptor system for aspect-oriented programming.
/**
* Global interceptors object containing request interceptors
*/
interface Interceptors {
request: {
use(fulfilled?: Function, rejected?: Function): number;
eject(id: number): void;
};
}
/**
* Create an intercepted version of a function
* @param fn - Function to wrap with interceptors
* @returns Intercepted function
*/
function interceptorify(fn: Function): Function;Environment type constants for runtime detection.
/**
* Environment type constants
*/
declare const ENV_TYPE: {
WEAPP: 'WEAPP'; // WeChat Mini Program
WEB: 'WEB'; // Web/H5 environment
RN: 'RN'; // React Native
SWAN: 'SWAN'; // Baidu Smart Program
ALIPAY: 'ALIPAY'; // Alipay Mini Program
TT: 'TT'; // ByteDance Mini Program
QQ: 'QQ'; // QQ Mini Program
JD: 'JD'; // JD Mini Program
};
/**
* Current application context
*/
interface CurrentContext {
app: any;
page: any;
component: any;
router: {
params: Record<string, string>;
path: string;
};
[key: string]: any;
}Component behavior definition system for reusable component logic.
/**
* Define reusable component behavior
* Note: Limited functionality in H5 environment
* @param behavior - Behavior definition object
* @returns Behavior constructor
*/
function Behavior(behavior: BehaviorDefinition): any;
interface BehaviorDefinition {
properties?: Record<string, any>;
data?: Record<string, any>;
methods?: Record<string, Function>;
behaviors?: any[];
created?(): void;
attached?(): void;
ready?(): void;
detached?(): void;
[key: string]: any;
}Plugin requirement system (not supported in H5 environment).
/**
* Require a plugin (not supported in H5)
* @param name - Plugin name
* @throws Always throws "not supported" error in H5
*/
function requirePlugin(name: string): never;Note: The plugin system is specific to Mini Program environments and is not available in H5. This function will always throw an error indicating the feature is not supported.
import Taro from "@tarojs/taro-h5";
// Configure pixel transformation for responsive design
Taro.initPxTransform({
designWidth: 750,
deviceRatio: {
640: 1.17,
750: 1,
828: 0.905
},
baseFontSize: 20,
targetUnit: 'rem'
});
// Set up global event listeners
Taro.eventCenter.on('user:login', (userData) => {
console.log('User logged in:', userData);
});
// Check environment
if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
console.log('Running in web environment');
}import Taro from "@tarojs/taro-h5";
function MyComponent() {
// Get current instance context
const instance = Taro.getCurrentInstance();
// Access router parameters
const { params } = instance?.router || {};
// Get current page stack
const pages = Taro.getCurrentPages();
const currentPage = pages[pages.length - 1];
// Use next tick for DOM updates
Taro.nextTick(() => {
console.log('DOM updated');
});
return <div>Component content</div>;
}import Taro from "@tarojs/taro-h5";
// Create custom events instance
const customEvents = new Taro.Events();
// Component A - emit event
customEvents.trigger('data:updated', { id: 1, name: 'Updated' });
// Component B - listen for event
customEvents.on('data:updated', (data) => {
console.log('Received data:', data);
});
// Global event communication
Taro.eventCenter.trigger('app:ready', { timestamp: Date.now() });Install with Tessl CLI
npx tessl i tessl/npm-tarojs--taro-h5