ArkTS 中导入(import)和导出(export)

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

一、基本导出(export)方式

1. 命名导出

// utils.ets
export function formatDate(date: Date): string {
  return date.toLocaleDateString();
}

export const APP_VERSION = '1.0.0';

export class Logger {
  static log(message: string) {
    console.log(message);
  }
}

2. 默认导出(每个文件只能有一个)

// MyComponent.ets
@Component
export default struct MyComponent {
  build() {
    Text('默认导出的组件')
  }
}

3. 混合导出

// config.ets
const apiBase = 'https://api.example.com';

export default {
  timeout: 5000,
  retryCount: 3
};

export { apiBase };

二、基本导入(import)方式

1. 导入命名导出

import { formatDate, APP_VERSION } from './utils';
import { Logger as AppLogger } from './utils'; // 重命名

@Entry
@Component
struct Example {
  build() {
    Column() {
      Text(`版本: ${APP_VERSION}`)
      Text(`日期: ${formatDate(new Date())}`)
    }
  }
}

2. 导入默认导出

import MyComponent from './MyComponent';
import CustomName from './MyComponent'; // 可以任意命名

@Entry
@Component
struct ParentComponent {
  build() {
    Column() {
      MyComponent()
      CustomName()
    }
  }
}

3. 导入所有导出(命名空间导入)

import * as utils from './utils';

@Entry
@Component
struct Example {
  build() {
    Column() {
      Text(utils.APP_VERSION)
      Button('记录')
        .onClick(() => {
          utils.Logger.log('按钮点击');
        })
    }
  }
}

三、特殊导入场景

1. 资源导入

import $r from 'app'; // 资源管理
import imageSrc from './assets/image.png'; // 图片资源

@Entry
@Component
struct ResourceExample {
  build() {
    Column() {
      Image($r('app.media.icon')) // 使用资源管理器
        .width(100)
        .height(100)
      Image(imageSrc) // 直接引用图片
        .width(100)
        .height(100)
    }
  }
}

2. 系统能力导入

import router from '@ohos.router'; // 页面路由
import featureAbility from '@ohos.ability.featureAbility'; // FA特性
import window from '@ohos.window'; // 窗口管理

@Entry
@Component
struct SystemExample {
  build() {
    Column() {
      Button('跳转页面')
        .onClick(() => {
          router.pushUrl({ url: 'pages/NextPage' });
        })
    }
  }
}

四、重新导出(Re-export)

1. 集中管理导出

// components/index.ets
export { default as Button } from './Button';
export { default as Input } from './Input';
export { default as Card } from './Card';

// 使用时
import { Button, Input } from '../components';

2. 重命名后导出

// utils/index.ets
export { formatDate as format } from './dateUtils';
export { Logger as AppLogger } from './logger';

五、动态导入(按需加载)

1. 基本用法

async function loadComponent() {
  const module = await import('./DynamicComponent');
  const Component = module.default;
  // 使用组件...
}

2. 配合路由使用

// 动态路由加载
router.pushUrl({
  url: 'pages/DetailPage',
  params: {
    loadComponent: () => import('./DetailComponent')
  }
});

六、类型导入

1. 仅导入类型

import type { Config } from './types';

function validateConfig(config: Config): boolean {
  // ...
}

2. 混合导入

import { type Config, default as App } from './app';

七、常见导入导出模式

1. 服务类导出

// apiService.ets
class ApiService {
  private static instance: ApiService;
  
  private constructor() {}
  
  static getInstance(): ApiService {
    if (!ApiService.instance) {
      ApiService.instance = new ApiService();
    }
    return ApiService.instance;
  }
  
  fetchData() {
    // ...
  }
}

export default ApiService;

// 使用
import ApiService from './apiService';
const api = ApiService.getInstance();

2. 组件库导出

// component-library/index.ets
export { default as PrimaryButton } from './PrimaryButton';
export { default as SecondaryButton } from './SecondaryButton';
export { default as InputField } from './InputField';
export { default as Modal } from './Modal';

// 使用
import { PrimaryButton, Modal } from 'component-library';

八、完整示例

1. 组件导出

// components/CustomButton.ets
@Component
export default struct CustomButton {
  @Prop label: string = '';
  @State pressed: boolean = false;

  build() {
    Button(this.label)
      .stateEffect(this.pressed)
      .onClick(() => {
        this.pressed = !this.pressed;
      })
  }
}

2. 工具类导出

// utils/calculation.ets
export function add(a: number, b: number): number {
  return a + b;
}

export function subtract(a: number, b: number): number {
  return a - b;
}

export default {
  multiply(a: number, b: number): number {
    return a * b;
  },
  divide(a: number, b: number): number {
    return a / b;
  }
};

3. 主页面导入

// pages/HomePage.ets
import CustomButton from '../components/CustomButton';
import calc, { add, subtract } from '../utils/calculation';
import $r from 'app';

@Entry
@Component
struct HomePage {
  @State result: number = 0;

  build() {
    Column() {
      Text(`结果: ${this.result}`)
        .fontSize(20)
      
      CustomButton({ label: '加5' })
        .onClick(() => {
          this.result = add(this.result, 5);
        })
      
      CustomButton({ label: '乘2' })
        .onClick(() => {
          this.result = calc.multiply(this.result, 2);
        })
      
      Image($r('app.media.logo'))
        .width(100)
        .height(100)
    }
  }
}

九、建议

  1. 命名规范

    • 组件使用PascalCase命名并默认导出
    • 工具函数使用camelCase命名
    • 常量使用UPPER_CASE命名
  2. 组件导入

    • 优先使用默认导入(import Component from './Component'
    • 保持组件命名首字母大写
  3. 工具库导入

    • 包含多个实用函数时推荐使用命名空间导入(import * as utils from './utils'
    • 避免命名冲突
  4. 性能考虑

    • 两种导入方式在打包后性能无差异
    • 按需导入比整体导入更有利于Tree Shaking
  5. 代码可读性

    • 保持导入方式的一致性
    • 对于第三方库,遵循库的导出风格
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值