DEV Community

苏杰豪
苏杰豪

Posted on

uni-app x Cross-Platform Getting Started and Practice: Develop HarmonyOS 5 Applications

uni-app x Cross-Platform Getting Started and Practice: Develop HarmonyOS 5 Applications

Course Introduction

What You Will Gain

  • Core logic of uni-app x for developing native HarmonyOS applications
  • Multi-platform interface adaptation thinking and code compatibility practice
  • Complete a publishable cross-platform application from 0 to 1
  • Acquire multi-platform application development capabilities (HarmonyOS Next/Android/iOS/WeChat Mini Program/Web)

Target Audience

  • HarmonyOS application development engineers who want to enter the cross-platform field
  • Technology enthusiasts who want to learn HarmonyOS and mini program development but lack practical cases
  • Partners who have learned uni-app and want to advance to the next-generation uni-app x technology stack
  • Mobile development engineers who want one codebase to cover multiple platforms
  • Enterprise developers or startup teams who need to quickly develop multi-platform applications

Course Overview

Application Icon

This course uses "Random Jokes" as a practical case to comprehensively analyze the cross-platform development process based on uni-app x. Through full-chain practice from environment setup, feature development to multi-platform adaptation, students will master the core syntax of uni-app x, cross-platform component invocation, screen adaptation techniques, and multi-platform (HarmonyOS Next/Android/iOS/WeChat Mini Program/Web) packaging and deployment capabilities. The course combines real development scenarios such as Huawei foldable screen adaptation and cloud packaging, focusing on practical implementation and cutting-edge technology coverage, helping developers quickly get started with cross-platform application development and accumulate project experience.

Course Highlights

  1. Practice-driven, learn and apply immediately: Using complete open-source projects as carriers, covering the full process from requirement analysis to online deployment, avoiding pure theoretical stacking, focusing on code implementation and problem solving (such as foldable screen adaptation, multi-platform style compatibility).
  2. Multi-platform adaptation core technology breakdown: In-depth analysis of uni-app x cross-platform principles, mastering differentiated adaptation strategies for different devices and platforms through hands-on practice like Huawei foldable screen adaptation, HarmonyOS platform signing configuration, and compatibility handling.
  3. Cutting-edge technology and ecosystem coverage: Combining HarmonyOS (HarmonyOS Next) development, Uni TypeScript syntax, SCSS style preprocessing and other technologies, adapting to current cross-platform development trends.

Platform Compatibility

  • HarmonyOS NEXT / HarmonyOS 5 ✅
  • Android ✅
  • iOS ✅
  • WeChat Mini Program ✅
  • Web (Browser) ✅

Running Effects

  • iPhone, Android, HarmonyOS Mate X (Unfolded), WeChat Mini Program

Running Effect 1

)

  • iPhone, Android, HarmonyOS Mate X (Folded), WeChat Mini Program

Running Effect 2

Technology Stack

  • UniApp X
  • Uni TypeScript
  • Vue 3

Development Tools

  • Operating System: MacOS 15.4.1
  • Editor: HBuilder X 4.65
  • HarmonyOS Development Environment: DevEco Studio 5.0.4 Release
  • Android Development Environment: Android Studio (version 2024.2)
  • iOS Development Environment: Xcode Version 16.1 (16B40)
  • Browser: Chrome 135.0.7049.85

uni-app x

uni-app x Introduction

uni-app x is the next-generation uni-app, a cross-platform application development engine that now supports compilation into HarmonyOS Next native applications (4.61+)

uni-app x includes the uvue rendering engine, uts language, uni components and APIs, and extension mechanisms.

uvue Rendering Engine

Quickly write pages using the vue3 framework, ultimately compiling into high-performance pure native interfaces for different platforms.

  1. Template-based writing
  2. Data two-way binding
  3. Component mechanism

On the HarmonyOS Next platform, uni-app x projects are compiled entirely into ArkTS + ArkUI code, essentially native HarmonyOS applications written with vue syntax.

uts Language

uts stands for uni typescript, a strongly-typed modern programming language. It supports cross-platform and will ultimately be compiled into native languages for different platforms, such as:

  • web/mini program platforms, compiled to JavaScript
  • HarmonyOS next platform, compiled to ArkTS
  • Android platform, compiled to Kotlin
  • iOS platform, compiled to Swift

uts is very similar to ts, but for cross-platform compatibility, uts has some constraints and platform-specific additions. See uts Language Introduction for details

Note: In ts, object types are often defined through interface or type, but in uts, you need to use type to define object types. Because interface has differences in kotlin and swift.

uni Components

uni-app x components are mainly divided into three categories:

  • Built-in basic components: such as view, text, image, scroll-view, input... etc., see Component List for details
  • Custom components: Components encapsulated by developers using vue syntax.
  • uts component plugins: Third-party components that can be downloaded through the Plugin Market.

Preparation

Development Environment Setup

  • Download and install HBuilderX editor
  • Create uni-app x project through HbuilderX

Project Directory Structure

├─pages             Directory for storing business page files
│  └─index
│     └─index.uvue  index page
├─static            Directory for storing local static resources referenced by the application (Note: static resources can only be stored here)
├─unpackage         Non-project code, generally stores compilation results for running or publishing
├─index.html        H5 page
├─main.uts          Vue initialization entry file
├─App.uvue          Application configuration, used to configure App global styles and listeners
├─pages.json        Configure page routing, navigation bar, tab bar and other page information
├─manifest.json     Configure application name, appid, logo, version and other packaging information
└─uni.scss          Built-in common style variables for uni-app
Enter fullscreen mode Exit fullscreen mode

Compile and Run

  • Install uni-app x compiler plugin
  • Compile and run HarmonyOS native application

Project Practice

Effect Preview

Image description

Image description

Material Download

Project Image Materials.zip

Structure and Styling

Use uni-app x component library to implement basic project layout.

Layout Key Points:

  • view component defaults to flex mode with vertical column direction
  • uni-app x styles are not inherited, text needs to be wrapped with text and styled separately

Reference Code:

<template>
  <view class="container">
    <!-- Card container -->
    <view class="card">
      <!-- Header title -->
      <view class="header">
        <text class="header-text">Random Jokes</text>
      </view>
      <!-- Scroll content area -->
      <scroll-view class="scroll-content">
        <text class="scroll-content-text">Loading jokes...</text>
      </scroll-view>
      <!-- Footer button -->
      <view class="footer">
        <button class="footer-button">Next One</button>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.container {
  /* Note 1: view defaults to flex with column direction */
  /* display: flex; */
  /* flex-direction: column;  */
  /* Note 2: uni-app x styles are not inherited, text needs to be wrapped with text and styled separately */
  /* font-size: 100rpx; */
  flex: 1;
  justify-content: center;
  align-items: center;
  background-color: #f6f6f6;
}

.card {
  width: 90%;
  border-radius: 20rpx;
  /* 1. Box shadow: X offset, Y offset, blur radius and color */
  box-shadow: 0 10rpx 30rpx #a7b3f9;
  /* iOS has compatibility issues, needs to be set to white actively */
  background-color: #fff;
}

.header {
  background-color: #1534f5;
  height: 110rpx;
  padding: 0 30rpx;
  /* iOS border-radius is not constrained by parent, needs to be set actively */
  border-radius: 20rpx 20rpx 0 0;

  /* 2. Center vertically on main axis */
  justify-content: center;

  /* 3. After adding lang="scss" to style, supports class nesting */
  /* 4. Text cannot inherit, need to define class names for text modifications */
  .header-text {
    font-size: 28rpx;
    font-weight: 700;
    color: #fff;
  }
}

.scroll-content {
  padding: 40rpx 30rpx;
  /* 5. Minimum height */
  min-height: 300rpx;

  .scroll-content-text {
    font-size: 30rpx;
    color: #3204ac;
    line-height: 45rpx;
  }
}

.footer {
  /* 6. Align horizontally to the right */
  align-items: flex-end;
  padding-bottom: 20rpx;
  padding-right: 20rpx;

  .footer-button {
    background-color: #1534f5;
    color: #fff;
    font-size: 26rpx;
    border-radius: 50rpx;
    padding: 6rpx 30rpx;
  }
}
</style>
Enter fullscreen mode Exit fullscreen mode

Business Logic

Reference Code:

<script setup lang="uts">
import { ref } from 'vue'

const jokeText = ref('Loading jokes...')

// Note: uni-app x needs to use type to define object types, using interface has compatibility issues
type ServiceData = {
  message : string
  data : string
}

function getJoke() {
  // Specify the backend return data type through generics
  uni.request<ServiceData>({
    url: 'https://hmajax.itheima.net/api/randjoke',
    method: 'GET',
    success: (res) => {
      // Android-compatible type writing
      const jokeStr = res.data?.data
      if (jokeStr !== null) {
        jokeText.value = jokeStr
      }
    },
    fail: () => {
      jokeText.value = 'Data retrieval failed, please check network...'
    }
  })
}
</script>

<template>
  <view class="container">
    <view class="card">
      <view class="header">
        <text class="header-text">Random Jokes</text>
      </view>
      <scroll-view class="scroll-content">
        <text class="scroll-content-text">{{ jokeText }}</text>
      </scroll-view>
      <view class="footer">
        <button class="footer-button" @click="getJoke()">Next One</button>
      </view>
    </view>
  </view>
</template>
Enter fullscreen mode Exit fullscreen mode

Lifecycle

Page Lifecycle

Page Lifecycle: https://doc.dcloud.net.cn/uni-app-x/page.html#lifecycle

Composition API Options API Description
onLoad onLoad Lifecycle callback listening for page load. Triggered when page loads. A page is only called once, parameters from the path opening current page can be obtained in onLoad parameters.
onPageShow onShow Lifecycle callback listening for page show. Triggered when page shows/enters foreground.
onReady onReady Lifecycle callback listening for page initial render completion. Triggered when page initial render is complete. A page is only called once, representing that the page is ready and can interact with the view layer.
onPageHide onHide Lifecycle callback listening for page hide. Triggered when page hides/enters background. Such as navigateTo or bottom tab switching to other pages, application entering background, etc.
onUnload onUnload Lifecycle callback listening for page unload. Triggered when page unloads. Such as redirectTo or navigateBack to other pages.
onResize onResize Triggered when page size changes
onBackPress onBackPress Listen for page return

Reference Code:

<script setup lang="uts">
// ...previous code omitted

// When page loads
onLoad(() => {
  // Get joke
  getJoke()
})
</script>
Enter fullscreen mode Exit fullscreen mode

Foldable Screen Adaptation

Notes:

  • vh unit can only be used on WeChat Mini Program and Web platforms, HarmonyOS, Android, iOS platforms do not support it
  • Properties like max-height, min-height can only use numbers or px units for multi-platform compatibility

Effect Preview:

Reference Code:

<script setup lang="uts">
// ...other code omitted

// Synchronously get window information, returned unit is px
const windowInfo = uni.getWindowInfo()
</script>

<template>
  <view class="container">
    <view class="card">
      <view class="header">
        <text class="header-text">Random Jokes</text>
      </view>
      <!-- Scroll content area -->
      <scroll-view
        class="scroll-content"
        :style="{ maxHeight: windowInfo.screenHeight * 0.66 + 'px' }"
      >
        <text class="scroll-content-text">{{ jokeText }}</text>
      </scroll-view>
      <view class="footer">
        <button class="footer-button" @click="getJoke()">Next One</button>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.scroll-content {
  padding: 40rpx 30rpx;
  // 5. Minimum height
  min-height: 300rpx;
  // vh unit can only be used on WeChat Mini Program and Web platforms, max-height, min-height only support numbers or px units
  /* #ifdef MP-WEIXIN || WEB */
  max-height: 66vh; /* Maximum height, 66% of screen height */
  /* #endif */
}
</style>
Enter fullscreen mode Exit fullscreen mode

HarmonyOS Application Signing Certificate

  • HarmonyOS debug certificate for real device debugging
  • HarmonyOS release certificate for publishing
  • AGC platform to create projects and applications
  • HBuilderX to configure HarmonyOS debug certificate

HarmonyOS Signing Certificate

DevEco Studio Hbuilder Notes
storeFile Private key store file .p12
storePassword Private key store password ·······
keyAlias Private key alias debugKey / releaseKey
keyPassword Private key password ·······
profile Signing profile file .p7b
certpath Certificate file .cer

AGC Platform Create Project and Application

There are many steps here, please patiently check each step until application creation is complete.

  1. Log in to AppGallery Connect, click "Development & Services".

  2. Click "Add Project" on the project page.

Image description

  1. Enter the project name on the "Create Project" page, then click "Finish".

Image description

  1. Select "Certificates, APP ID and Profile", select "APP ID" in the left navigation bar, after entering the page, click "New" in the upper right corner.

Image description

HarmonyOS Debug Certificate

  1. Open the manifest.json file, select the "HarmonyOS App Configuration" menu, then click the "Configure" button for debug certificate.

Image description

  1. In the debug certificate configuration, check that "Application Package Name" and "Running Device" are correct, then click the "Auto Apply for Debug Certificate" button.

Image description

HarmonyOS Release Certificate

HarmonyOS release certificates cannot be automatically generated, the process has many steps, please refer to the video explanation, patiently check each step until configuration is complete.

  • Release certificate files

Image description

  • Configure release certificate

Image description

  • Release certificate notes

Signing profile file .p7b cannot be reused because it contains package name information, other certificate files can be reused across multiple projects, please remember the private key alias and password.

DevEco Studio Hbuilder Notes
storeFile Private key store file .p12
storePassword Private key store password ·······
keyAlias Private key alias debugKey / releaseKey
keyPassword Private key password ·······
profile Signing profile file .p7b
certpath Certificate file .cer

HarmonyOS Application Packaging and Distribution

HarmonyOS Application Local Packaging

After configuring HarmonyOS release certificate, you can proceed with HarmonyOS application local packaging, ultimately generating a signed .app installation package.

Image description

HarmonyOS Application Publishing

Upload the signed .app installation package on the AGC platform, please refer to the video explanation or check the official documentation: Publishing HarmonyOS Applications (HarmonyOS NEXT)

Image description

Android Application Cloud Packaging (Additional)

Android applications can be directly packaged using cloud certificates, ultimately generating a signed .apk installation package.

Users can upload the apk to various Android app stores.

Image description

Top comments (0)