一、模塊類型概述

二、添加新模塊(Add New Module)
入口路徑:
右鍵工程根目錄 >New > Module
菜單File > New > Module
操作步驟:
選擇模板(如Empty Ability或Shared Library)。
配置模塊信息:
Module name:不能與工程名重復(fù)(如feature_payment)。
Module type:選擇Entry?或Feature(默認(rèn)Feature)。
Device type:勾選支持的設(shè)備(如 Phone、Tablet)。
完成創(chuàng)建后,模塊會(huì)生成獨(dú)立的src、resources?和module.json5。
三、模塊功能擴(kuò)展:添加 Ability 與 Page
1. 添加 Ability(核心組件)
Stage 模型(主推):
UIAbility:帶界面的組件(如頁面、彈窗)。
右鍵模塊ets?目錄 >New > Ability > UIAbility,設(shè)置名稱并勾選Launcher ability(桌面圖標(biāo))。
ExtensionAbility:無界面的擴(kuò)展功能(如后臺(tái)服務(wù)、數(shù)據(jù)備份)。
右鍵模塊 >New > Extension Ability,選擇類型(如BackupAbility)。
FA 模型(兼容舊項(xiàng)目):
右鍵模塊js?目錄 >New > Ability,選擇Page Ability或Service Ability。
2. 添加 Page(頁面)
適用場景:ArkTS Stage 模型工程,用于構(gòu)建多頁面應(yīng)用。
操作步驟:
右鍵模塊src/main/ets/pages?>New > Page。
選擇模板(如Empty Page或Map Page),輸入名稱(如OrderPage)。
生成文件OrderPage.ets,通過路由跳轉(zhuǎn):
import router from '@ohos.router';
router.pushUrl({ url: 'pages/OrderPage' }); // 跳轉(zhuǎn)至新頁面
四、添加服務(wù)卡片(Service Widget)
1. 創(chuàng)建流程
右鍵模塊 > New > Service Widget
選擇卡片模板:
2x2
2x4
4x4
配置參數(shù)(可默認(rèn)):

生成文件:
resources/base/profile/
? └── weather_widget.json? // 卡片配置文件
ets/widget/
? └── WeatherWidget.ets? // 卡片邏輯
?2. 卡片配置文件示例
{
? "forms": [
? ? {
? ? ? "name": "widget",
? ? ? "displayName": "$string:widget_display_name",
? ? ? "description": "$string:widget_desc",
? ? ? "src": "./ets/widget/pages/WidgetCard.ets",
? ? ? "uiSyntax": "arkts",
? ? ? "window": {
? ? ? ? "designWidth": 720,
? ? ? ? "autoDesignWidth": true
? ? ? },
? ? ? "colorMode": "auto",
? ? ? "isDynamic": true,
? ? ? "isDefault": true,
? ? ? "updateEnabled": false,
? ? ? "scheduledUpdateTime": "10:30",
? ? ? "updateDuration": 1,
? ? ? "defaultDimension": "1*2",
? ? ? "supportDimensions": [
? ? ? ? "1*2",
? ? ? ? "2*2"
? ? ? ]
? ? }
? ]
}
?五、導(dǎo)入示例工程(Import Sample)
1. 導(dǎo)入 Sample 工程(快速學(xué)習(xí))
操作步驟:
確保已安裝 Git(菜單File > Settings > Version Control > Git,測試連接)。
歡迎頁點(diǎn)擊More Actions > Import Sample,選擇官方示例(如Preferences?配置模塊)。
等待同步完成,查看模塊結(jié)構(gòu)(如entry?主模塊 +feature_settings?特性模塊)。
注意:
網(wǎng)絡(luò)受限需配置 Git 代理(git config --global http.proxy http://proxy:port)。
2. 刪除模塊
操作步驟:
右鍵模塊目錄 >Delete,確認(rèn)刪除文件。
手動(dòng)清理工程級(jí)配置:
build-profile.json5?中移除模塊相關(guān)配置。
app.json5(Stage)或config.json(FA)中刪除模塊引用。
六、模塊開發(fā)最佳實(shí)踐
1. 模塊化設(shè)計(jì)原則
職責(zé)分離:
entry?模塊:僅包含啟動(dòng)邏輯和全局配置。
feature?模塊:獨(dú)立功能(如feature_login、feature_share),通過接口與主模塊通信。
資源復(fù)用:
公共資源(如字體、顏色)放在AppScope/resources?目錄,供所有模塊共享。
私有資源存放在模塊resources?目錄,避免命名沖突。
2. 跨模塊通信
EventBus:通過全局事件總線傳遞數(shù)據(jù)(如@AppStorage?或三方庫EventCenter)。
接口暴露:在Library?模塊中定義接口,Entry/Feature?模塊實(shí)現(xiàn):
// Library模塊
export interface PaymentService {
? pay(amount: number): boolean;
}
// Feature模塊實(shí)現(xiàn)
export class AlipayService implements PaymentService { ... }
3. 構(gòu)建與調(diào)試
單獨(dú)構(gòu)建模塊:右鍵模塊 >Build Module,生成獨(dú)立.hap?包(用于動(dòng)態(tài)加載)。
調(diào)試特定模塊:在工具欄選擇模塊名稱,點(diǎn)擊Run或Debug(如entry?或feature_payment)。
##鴻蒙開發(fā)工具##DevEco Studio##商務(wù)#