For larger applications, it is beneficial to use modules to create cleaner separations of concerns for your apps. For example, a module for UI related code, a module for API code, a module for data repository code etc.
Multi-module apps can also make an application easier to test.
Modules in Harmony OS
Create a module using File > New > Module
.
- To create a module for non-UI related code in an app, create a Shared Library
- To create a module for UI code (e.g. a reusable set of UI components for an app), create a Visual Library.
- To create a module that is a stand-alone module but not part of an app, create a Static Library.
- To create a module that integrates with C++ code, create a Native C++ module.
Linking modules in your app
To use a module in an app, you must declare it as a dependency. To do this:
1. Open the oh-package.json5
file in the module that needs to use another module.
2. In the set of dependencies, reference the module using the path relative to the current module, e.g. "file:../SharedLibrary"
For example, in a module called entry
, you can add the module SharedLibrary
as a dependency with the path to the module and a name.
{
"name": "entry",
"version": "1.0.0",
"description": "Please describe the basic information.",
"dependencies": {
"SharedLib": "file:../SharedLibrary"
}
}
3. Import types from the module by using the module name as follows:
import {add} from 'SharedLib';
Exposing features from a module
When writing a module (such as a Shared Library), you have to declare which features are exported - this is the public interface of the module and is the code that can be used by other modules.
To expose features, you use the node package manager mechanism by declaring exports in an Index.ets
file that is found in the root of the module.
For example, to allow other modules to use the add
function from the module SharedLibrary
, export is as follows:
The types that can be exported include classes, types and functions.
DevEco Studio Run Config
In order to run an app that uses multiple modules, you must edit the run configuration to:
1. Keep Application Data
2. Deploy multiple HAP packages
OHOS Documentation
You can find out more in the OpenHarmony documentation here:
- https://docs.openharmony.cn/pages/v4.1/en/application-dev/quick-start/in-app-hsp.md