arkts-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ArkTS 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(传统版)

DecoratorUsageDescription
@State
@State count: number = 0
Component internal state
@Prop
@Prop title: string
Parent → Child (one-way)
@Link
@Link value: number
Parent ↔ Child (two-way, use
$varName
)
@Provide/@Consume
Cross-levelAncestor → Descendant
@Observed/@ObjectLink
Nested objectsDeep object observation
装饰器用法说明
@State
@State count: number = 0
组件内部状态
@Prop
@Prop title: string
父组件 → 子组件(单向)
@Link
@Link value: number
父组件 ↔ 子组件(双向,使用
$varName
@Provide/@Consume
跨层级祖先组件 → 后代组件
@Observed/@ObjectLink
嵌套对象深度对象监听

V2 (Recommended - API 12+)

V2(推荐使用 - API 12+)

DecoratorUsageDescription
@ComponentV2
@ComponentV2 struct MyComp
Enable V2 state management
@Local
@Local count: number = 0
Internal state (no external init)
@Param
@Param title: string = ""
Parent → Child (one-way, efficient)
@Event
@Event onChange: () => void
Child → Parent (callback)
@ObservedV2
@ObservedV2 class Data
Class observation
@Trace
@Trace name: string
Property-level tracking
@Computed
@Computed get value()
Cached computed properties
@Monitor
@Monitor('prop') onFn()
Watch changes with before/after
@Provider/@Consumer
Cross-levelTwo-way sync across tree
See references/state-management-v2.md for complete V2 guide.
装饰器用法说明
@ComponentV2
@ComponentV2 struct MyComp
启用V2状态管理
@Local
@Local count: number = 0
内部状态(无需外部初始化)
@Param
@Param title: string = ""
父组件 → 子组件(单向,高效)
@Event
@Event onChange: () => void
子组件 → 父组件(回调)
@ObservedV2
@ObservedV2 class Data
类监听
@Trace
@Trace name: string
属性级跟踪
@Computed
@Computed get value()
缓存计算属性
@Monitor
@Monitor('prop') onFn()
监听属性变化,支持前后回调
@Provider/@Consumer
跨层级组件树间双向同步
完整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:
ProhibitedUse Instead
any
,
unknown
Explicit types, interfaces
var
let
,
const
Dynamic property access
obj['key']
Fixed object structure
for...in
,
delete
,
with
for...of
, array methods
#privateField
private
keyword
Structural typingExplicit
implements
/
extends
See references/migration-guide.md for complete TypeScript → ArkTS migration details.
为了性能和安全性,ArkTS相比TypeScript有更严格的规则:
禁止使用替代方案
any
,
unknown
显式类型、接口
var
let
,
const
动态属性访问
obj['key']
固定对象结构
for...in
,
delete
,
with
for...of
, 数组方法
#privateField
private
关键字
结构类型显式
implements
/
extends
完整的TypeScript → ArkTS迁移细节请查看references/migration-guide.md

Command Line Build (hvigorw)

命令行构建(hvigorw)

hvigorw is the Hvigor wrapper tool for command-line builds.
bash
undefined
hvigorw是用于命令行构建的Hvigor封装工具。
bash
undefined

Common 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
undefined
codelinter是用于ArkTS/TS文件的代码检查与修复工具。
bash
undefined

Basic 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
undefined
hstack可将发布版构建中的混淆崩溃堆栈解析回源代码位置。
bash
undefined

Parse 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.json5
:
json
"arkOptions": {
  "obfuscation": {
    "ruleOptions": {
      "enable": true,
      "files": ["./obfuscation-rules.txt"]
    }
  }
}
Common rules in
obfuscation-rules.txt
:
text
-enable-property-obfuscation      # Property name obfuscation
-enable-toplevel-obfuscation      # Top-level scope obfuscation
-enable-filename-obfuscation      # Filename obfuscation
-keep-property-name apiKey        # Whitelist specific names
See references/arkguard-obfuscation.md for complete guide.
build-profile.json5
中启用:
json
"arkOptions": {
  "obfuscation": {
    "ruleOptions": {
      "enable": true,
      "files": ["./obfuscation-rules.txt"]
    }
  }
}
obfuscation-rules.txt
中的常用规则:
text
-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
  • 状态管理V2references/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
    harmonyos-build-deploy
    skill for building, packaging, and device installation
  • 构建与部署:如需了解构建、打包和设备安装相关内容,请查看
    harmonyos-build-deploy
    技能