鸿蒙开发中,index.ets 文件有哪些用法?

本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新

在鸿蒙(HarmonyOS)应用开发中,index.ets 文件的具体用法会根据其在项目中的位置(如主模块 entry、功能模块 feature 或共享模块 shared)而有所不同。以下是不同场景下的详细使用方法和示例:

一、主模块(entry/src/main/ets)中的 index.ets

1. 核心作用
  • 应用入口:整个应用的启动入口,负责初始化全局配置和路由。
  • 生命周期管理:监听应用级生命周期事件。
2. 典型代码结构
// entry/src/main/ets/pages/index.ets
import router from '@ohos.router';
import AbilityStage from '@ohos.app.ability.AbilityStage';

export default {
  onCreate() {
    console.info('Application onCreate');

    // 1. 配置全局路由
    router.addRoute({
      name: 'main',
      path: '/main',
      component: 'pages/MainPage' // 对应MainPage.ets
    });

    // 2. 设置默认首页
    router.pushUrl({ url: '/main' });

    // 3. 注册全局异常处理器
    errorHandler.register((err) => {
      console.error('Global error:', err);
    });
  },

  onDestroy() {
    console.info('Application onDestroy');
  }
}
3. 关联文件
  • EntryAbility.ets:能力层入口,与 index.ets 配合使用。
// entry/src/main/ets/entryability/EntryAbility.ets
export default class EntryAbility extends Ability {
  onWindowStageCreate(windowStage: WindowStage) {
    windowStage.loadContent('pages/index', (err) => {
      if (err) console.error('Load content failed:', err);
    });
  }
}

二、功能模块(feature/src/main/ets)中的 index.ets

1. 核心作用
  • 模块独立入口:作为功能模块的对外暴露点。
  • 封装实现细节:对外提供统一接口,隐藏内部页面跳转逻辑。
2. 典型代码结构
// features/news/src/main/ets/pages/index.ets
import router from '@ohos.router';

export default {
  // 暴露给其他模块的API
  openNewsDetail(newsId: string) {
    router.pushUrl({
      url: `pages/NewsDetailPage`,
      params: { newsId } // 传递参数
    });
  },

  // 模块内部路由配置
  private setupRoutes() {
    router.addRoute({
      name: 'newsList',
      path: '/news/list',
      component: 'pages/NewsListPage'
    });
  }
}

3. 其他模块调用方式

// 在其他模块中调用
import news from '@ohos.news'; // 假设news是已配置的模块依赖

Button('查看新闻')
  .onClick(() => news.openNewsDetail('123'))

三、共享模块(shared/src/main/ets)中的 index.ets

1. 核心作用
  • 集中导出:统一导出模块内的工具类、组件和资源。
  • 避免路径耦合:其他模块通过 import from '@ohos/shared' 即可访问。
2. 典型代码结构
// shared/src/main/ets/index.ets
export { default as FancyButton } from './components/FancyButton';
export { formatDate } from './utils/DateUtils';
export { default as globalStyles } from './styles/GlobalStyles';

3. 其他模块引用示例

import { FancyButton, formatDate } from '@ohos/shared';

@Entry
@Component
struct MyPage {
  build() {
    Column() {
      FancyButton('点击') // 使用共享组件
      Text(formatDate(new Date())) // 使用共享工具
    }
  }
}

四、特殊场景用法

1. 多设备适配入口
// index.ets 设备分支逻辑
import deviceInfo from '@ohos.deviceInfo';

const isTablet = deviceInfo.deviceType === 'tablet';

export default {
  onCreate() {
    if (isTablet) {
      router.pushUrl({ url: '/tablet/MainPage' });
    } else {
      router.pushUrl({ url: '/phone/MainPage' });
    }
  }
}
2. 测试环境初始化
// index.ets 环境配置
import config from './config';

export default {
  onCreate() {
    if (config.env === 'test') {
      mock.initAll(); // 初始化测试Mock数据
    }
  }
}

五、最佳实践建议

  1. 路由分层管理

// 建议的路由目录结构
/src/main/ets
├── routes
│   ├── index.ets      # 路由出口文件
│   ├── MainRoutes.ets # 主路由配置
│   └── AuthRoutes.ets # 认证路由

   2. 避免在index.ets中写UI

// ❌ 错误做法 - 混合逻辑与UI
@Entry
@Component
export struct Index {
  build() {
    Text('不应在这里写UI')
  }
}

// ✅ 正确做法 - 仅做路由转发
export default {
  onCreate() {
    router.pushUrl('/main');
  }
}

3. TypeScript类型支持

// 为模块导出添加类型声明
// shared/index.d.ts
declare module '@ohos/shared' {
  export const FancyButton: typeof import('./components/FancyButton').default;
  export function formatDate(date: Date): string;
}

通过以上分场景的用法,index.ets 文件可以高效地组织模块入口逻辑,保持代码的可维护性和扩展性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值