arkts-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseArkTS Development
ArkTS开发
Build HarmonyOS applications using ArkTS and the ArkUI declarative UI framework.
使用ArkTS和ArkUI声明式UI框架构建HarmonyOS应用。
Quick Start
快速入门
Create a basic component:
typescript
@Entry
@Component
struct HelloWorld {
@State message: string = 'Hello, ArkTS!';
build() {
Column() {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
Button('Click Me')
.onClick(() => { this.message = 'Button Clicked!'; })
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}创建基础组件:
typescript
@Entry
@Component
struct HelloWorld {
@State message: string = 'Hello, ArkTS!';
build() {
Column() {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
Button('Click Me')
.onClick(() => { this.message = 'Button Clicked!'; })
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}State Management Decorators
状态管理装饰器
V1 (Traditional)
V1(传统版)
| Decorator | Usage | Description |
|---|---|---|
| | Component internal state |
| | Parent → Child (one-way) |
| | Parent ↔ Child (two-way, use |
| Cross-level | Ancestor → Descendant |
| Nested objects | Deep object observation |
| 装饰器 | 用法 | 说明 |
|---|---|---|
| | 组件内部状态 |
| | 父组件 → 子组件(单向) |
| | 父组件 ↔ 子组件(双向,使用 |
| 跨层级 | 祖先组件 → 后代组件 |
| 嵌套对象 | 深度对象监听 |
V2 (Recommended - API 12+)
V2(推荐使用 - API 12+)
| Decorator | Usage | Description |
|---|---|---|
| | Enable V2 state management |
| | Internal state (no external init) |
| | Parent → Child (one-way, efficient) |
| | Child → Parent (callback) |
| | Class observation |
| | Property-level tracking |
| | Cached computed properties |
| | Watch changes with before/after |
| Cross-level | Two-way sync across tree |
See references/state-management-v2.md for complete V2 guide.
| 装饰器 | 用法 | 说明 |
|---|---|---|
| | 启用V2状态管理 |
| | 内部状态(无需外部初始化) |
| | 父组件 → 子组件(单向,高效) |
| | 子组件 → 父组件(回调) |
| | 类监听 |
| | 属性级跟踪 |
| | 缓存计算属性 |
| | 监听属性变化,支持前后回调 |
| 跨层级 | 组件树间双向同步 |
完整V2指南请查看references/state-management-v2.md。
Common Layouts
常用布局
typescript
// Vertical
Column({ space: 10 }) { Text('A'); Text('B'); }
.alignItems(HorizontalAlign.Center)
// Horizontal
Row({ space: 10 }) { Text('A'); Text('B'); }
.justifyContent(FlexAlign.SpaceBetween)
// Stack (overlay)
Stack({ alignContent: Alignment.Center }) {
Image($r('app.media.bg'))
Text('Overlay')
}
// List with ForEach
List({ space: 10 }) {
ForEach(this.items, (item: string) => {
ListItem() { Text(item) }
}, (item: string) => item)
}typescript
// 垂直布局
Column({ space: 10 }) { Text('A'); Text('B'); }
.alignItems(HorizontalAlign.Center)
// 水平布局
Row({ space: 10 }) { Text('A'); Text('B'); }
.justifyContent(FlexAlign.SpaceBetween)
// 堆叠布局(覆盖)
Stack({ alignContent: Alignment.Center }) {
Image($r('app.media.bg'))
Text('Overlay')
}
// 带ForEach的列表
List({ space: 10 }) {
ForEach(this.items, (item: string) => {
ListItem() { Text(item) }
}, (item: string) => item)
}Component Lifecycle
组件生命周期
typescript
@Entry
@Component
struct Page {
aboutToAppear() { /* Init data */ }
onPageShow() { /* Page visible */ }
onPageHide() { /* Page hidden */ }
aboutToDisappear() { /* Cleanup */ }
build() { Column() { Text('Page') } }
}typescript
@Entry
@Component
struct Page {
aboutToAppear() { /* 初始化数据 */ }
onPageShow() { /* 页面可见 */ }
onPageHide() { /* 页面隐藏 */ }
aboutToDisappear() { /* 清理资源 */ }
build() { Column() { Text('Page') } }
}Navigation
导航
typescript
import { router } from '@kit.ArkUI';
// Push
router.pushUrl({ url: 'pages/Detail', params: { id: 123 } });
// Replace
router.replaceUrl({ url: 'pages/New' });
// Back
router.back();
// Get params
interface RouteParams {
id: number;
title?: string;
}
const params = router.getParams() as RouteParams;typescript
import { router } from '@kit.ArkUI';
// 跳转页面
router.pushUrl({ url: 'pages/Detail', params: { id: 123 } });
// 替换页面
router.replaceUrl({ url: 'pages/New' });
// 返回上一页
router.back();
// 获取参数
interface RouteParams {
id: number;
title?: string;
}
const params = router.getParams() as RouteParams;Network Request
网络请求
typescript
import { http } from '@kit.NetworkKit';
const req = http.createHttp();
const res = await req.request('https://api.example.com/data', {
method: http.RequestMethod.GET,
header: { 'Content-Type': 'application/json' }
});
if (res.responseCode === 200) {
const data = JSON.parse(res.result as string);
}
req.destroy();typescript
import { http } from '@kit.NetworkKit';
const req = http.createHttp();
const res = await req.request('https://api.example.com/data', {
method: http.RequestMethod.GET,
header: { 'Content-Type': 'application/json' }
});
if (res.responseCode === 200) {
const data = JSON.parse(res.result as string);
}
req.destroy();Local Storage
本地存储
typescript
import { preferences } from '@kit.ArkData';
const prefs = await preferences.getPreferences(this.context, 'store');
await prefs.put('key', 'value');
await prefs.flush();
const val = await prefs.get('key', 'default');typescript
import { preferences } from '@kit.ArkData';
const prefs = await preferences.getPreferences(this.context, 'store');
await prefs.put('key', 'value');
await prefs.flush();
const val = await prefs.get('key', 'default');ArkTS Language Constraints
ArkTS语言约束
ArkTS enforces stricter rules than TypeScript for performance and safety:
| Prohibited | Use Instead |
|---|---|
| Explicit types, interfaces |
| |
Dynamic property access | Fixed object structure |
| |
| |
| Structural typing | Explicit |
See references/migration-guide.md for complete TypeScript → ArkTS migration details.
为了性能和安全性,ArkTS相比TypeScript有更严格的规则:
| 禁止使用 | 替代方案 |
|---|---|
| 显式类型、接口 |
| |
动态属性访问 | 固定对象结构 |
| |
| |
| 结构类型 | 显式 |
完整的TypeScript → ArkTS迁移细节请查看references/migration-guide.md。
Command Line Build (hvigorw)
命令行构建(hvigorw)
hvigorw is the Hvigor wrapper tool for command-line builds.
bash
undefinedhvigorw是用于命令行构建的Hvigor封装工具。
bash
undefinedCommon build tasks
常用构建任务
hvigorw clean # Clean build directory
hvigorw assembleHap -p buildMode=debug # Build Hap (debug)
hvigorw assembleApp -p buildMode=release # Build App (release)
hvigorw assembleHar # Build Har library
hvigorw assembleHsp # Build Hsp
hvigorw clean # 清理构建目录
hvigorw assembleHap -p buildMode=debug # 构建HAP包(调试版)
hvigorw assembleApp -p buildMode=release # 构建应用(发布版)
hvigorw assembleHar # 构建HAR库
hvigorw assembleHsp # 构建HSP
Build specific module
构建指定模块
hvigorw assembleHap -p module=entry@default --mode module
hvigorw assembleHap -p module=entry@default --mode module
Run tests
运行测试
hvigorw onDeviceTest -p module=entry -p coverage=true
hvigorw test -p module=entry # Local test
hvigorw onDeviceTest -p module=entry -p coverage=true
hvigorw test -p module=entry # 本地测试
CI/CD recommended
CI/CD推荐用法
hvigorw assembleApp -p buildMode=release --no-daemon
Common parameters:
| Parameter | Description |
|-----------|-------------|
| `-p buildMode={debug\|release}` | Build mode |
| `-p product={name}` | Target product (default: default) |
| `-p module={name}@{target}` | Target module (with `--mode module`) |
| `--no-daemon` | Disable daemon (recommended for CI) |
| `--analyze=advanced` | Enable build analysis |
| `--optimization-strategy=memory` | Memory-optimized build |
See [references/hvigor-commandline.md](references/hvigor-commandline.md) for complete command reference.hvigorw assembleApp -p buildMode=release --no-daemon
常用参数:
| 参数 | 说明 |
|-----------|-------------|
| `-p buildMode={debug\|release}` | 构建模式 |
| `-p product={name}` | 目标产品(默认:default) |
| `-p module={name}@{target}` | 目标模块(需搭配`--mode module`) |
| `--no-daemon` | 禁用守护进程(CI场景推荐) |
| `--analyze=advanced` | 启用构建分析 |
| `--optimization-strategy=memory` | 内存优化构建 |
完整命令参考请查看[references/hvigor-commandline.md](references/hvigor-commandline.md)。Code Linter (codelinter)
代码检查工具(codelinter)
codelinter is the code checking and fixing tool for ArkTS/TS files.
bash
undefinedcodelinter是用于ArkTS/TS文件的代码检查与修复工具。
bash
undefinedBasic usage
基础用法
codelinter # Check current project
codelinter /path/to/project # Check specified project
codelinter -c ./code-linter.json5 # Use custom rules
codelinter # 检查当前项目
codelinter /path/to/project # 检查指定项目
codelinter -c ./code-linter.json5 # 使用自定义规则
Check and auto-fix
检查并自动修复
codelinter --fix
codelinter -c ./code-linter.json5 --fix
codelinter --fix
codelinter -c ./code-linter.json5 --fix
Output formats
输出格式
codelinter -f json -o ./report.json # JSON report
codelinter -f html -o ./report.html # HTML report
codelinter -f json -o ./report.json # JSON格式报告
codelinter -f html -o ./report.html # HTML格式报告
Incremental check (Git changes only)
增量检查(仅检查Git变更文件)
codelinter -i
codelinter -i
CI/CD with exit codes
CI/CD退出码配置
codelinter --exit-on error,warn # Non-zero exit on error/warn
| Parameter | Description |
|-----------|-------------|
| `-c, --config <file>` | Specify rules config file |
| `--fix` | Auto-fix supported issues |
| `-f, --format` | Output format: default/json/xml/html |
| `-o, --output <file>` | Save result to file |
| `-i, --incremental` | Check only Git changed files |
| `-p, --product <name>` | Specify product |
| `-e, --exit-on <levels>` | Exit code levels: error,warn,suggestion |
See [references/codelinter.md](references/codelinter.md) for complete reference.codelinter --exit-on error,warn # 出现错误/警告时返回非零退出码
| 参数 | 说明 |
|-----------|-------------|
| `-c, --config <file>` | 指定规则配置文件 |
| `--fix` | 自动修复支持的问题 |
| `-f, --format` | 输出格式:default/json/xml/html |
| `-o, --output <file>` | 将结果保存至文件 |
| `-i, --incremental` | 仅检查Git变更的文件 |
| `-p, --product <name>` | 指定产品 |
| `-e, --exit-on <levels>` | 触发非零退出码的级别:error,warn,suggestion |
完整参考请查看[references/codelinter.md](references/codelinter.md)。Stack Trace Parser (hstack)
堆栈跟踪解析工具(hstack)
hstack parses obfuscated crash stacks from Release builds back to source code locations.
bash
undefinedhstack可将发布版构建中的混淆崩溃堆栈解析回源代码位置。
bash
undefinedParse crash files directory
解析崩溃文件目录
hstack -i crashDir -o outputDir -s sourcemapDir -n nameCacheDir
hstack -i crashDir -o outputDir -s sourcemapDir -n nameCacheDir
Parse with C++ symbols
解析包含C++符号的堆栈
hstack -i crashDir -o outputDir -s sourcemapDir --so soDir -n nameCacheDir
hstack -i crashDir -o outputDir -s sourcemapDir --so soDir -n nameCacheDir
Parse single crash stack
解析单个崩溃堆栈
hstack -c "at func (entry|entry|1.0.0|src/main/ets/pages/Index.ts:58:58)" -s sourcemapDir
| Parameter | Description |
|-----------|-------------|
| `-i, --input` | Crash files directory |
| `-c, --crash` | Single crash stack string |
| `-o, --output` | Output directory (or file with `-c`) |
| `-s, --sourcemapDir` | Sourcemap files directory |
| `--so, --soDir` | Shared object (.so) files directory |
| `-n, --nameObfuscation` | NameCache files directory |
Requirements:
- Must provide either `-i` or `-c` (not both)
- Must provide at least `-s` or `--so`
- For method name restoration, provide both `-s` and `-n`
See [references/hstack.md](references/hstack.md) for complete reference.hstack -c "at func (entry|entry|1.0.0|src/main/ets/pages/Index.ts:58:58)" -s sourcemapDir
| 参数 | 说明 |
|-----------|-------------|
| `-i, --input` | 崩溃文件目录 |
| `-c, --crash` | 单个崩溃堆栈字符串 |
| `-o, --output` | 输出目录(使用`-c`时为输出文件) |
| `-s, --sourcemapDir` | Sourcemap文件目录 |
| `--so, --soDir` | 共享对象(.so)文件目录 |
| `-n, --nameObfuscation` | NameCache文件目录 |
要求:
- 必须提供`-i`或`-c`(不能同时提供)
- 必须至少提供`-s`或`--so`
- 如需恢复方法名,需同时提供`-s`和`-n`
完整参考请查看[references/hstack.md](references/hstack.md)。Code Obfuscation (ArkGuard)
代码混淆(ArkGuard)
Enable in :
build-profile.json5json
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": true,
"files": ["./obfuscation-rules.txt"]
}
}
}Common rules in :
obfuscation-rules.txttext
-enable-property-obfuscation # Property name obfuscation
-enable-toplevel-obfuscation # Top-level scope obfuscation
-enable-filename-obfuscation # Filename obfuscation
-keep-property-name apiKey # Whitelist specific namesSee references/arkguard-obfuscation.md for complete guide.
在中启用:
build-profile.json5json
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": true,
"files": ["./obfuscation-rules.txt"]
}
}
}obfuscation-rules.txttext
-enable-property-obfuscation # 属性名混淆
-enable-toplevel-obfuscation # 顶级作用域混淆
-enable-filename-obfuscation # 文件名混淆
-keep-property-name apiKey # 白名单特定名称完整指南请查看references/arkguard-obfuscation.md。
Reference Files
参考文档
- State Management V2: references/state-management-v2.md - Complete guide to V2 state management (@ComponentV2, @Local, @Param, @Event, @ObservedV2, @Trace, @Computed, @Monitor, @Provider, @Consumer)
- Migration Guide: references/migration-guide.md - Complete TypeScript to ArkTS migration rules and examples
- Component Patterns: references/component-patterns.md - Advanced component patterns and best practices
- API Reference: references/api-reference.md - Common HarmonyOS APIs
- ArkGuard Obfuscation: references/arkguard-obfuscation.md - Code obfuscation configuration and troubleshooting
- Hvigor Command Line: references/hvigor-commandline.md - Complete hvigorw build tool reference
- CodeLinter: references/codelinter.md - Code checking and fixing tool
- Hstack: references/hstack.md - Crash stack trace parser for Release builds
- 状态管理V2:references/state-management-v2.md - V2状态管理完整指南(@ComponentV2、@Local、@Param、@Event、@ObservedV2、@Trace、@Computed、@Monitor、@Provider、@Consumer)
- 迁移指南:references/migration-guide.md - TypeScript转ArkTS完整迁移规则与示例
- 组件模式:references/component-patterns.md - 高级组件模式与最佳实践
- API参考:references/api-reference.md - 常用HarmonyOS API
- ArkGuard混淆:references/arkguard-obfuscation.md - 代码混淆配置与故障排除
- Hvigor命令行:references/hvigor-commandline.md - Hvigorw构建工具完整参考
- 代码检查工具:references/codelinter.md - 代码检查与修复工具
- 堆栈解析工具:references/hstack.md - 发布版构建崩溃堆栈跟踪解析工具
Development Environment
开发环境
- IDE: DevEco Studio
- SDK: HarmonyOS SDK
- Simulator: Built-in DevEco Studio emulator
- IDE:DevEco Studio
- SDK:HarmonyOS SDK
- 模拟器:DevEco Studio内置模拟器
Related Skills
相关技能
- Build & Deploy: See skill for building, packaging, and device installation
harmonyos-build-deploy
- 构建与部署:如需了解构建、打包和设备安装相关内容,请查看技能
harmonyos-build-deploy