支持多bundle场景下可以跨bundle访问图片资源的功能(图片无类型限制)
Access rate limit exceeded. Please log in to continue.
Document Template: v0.4.2
react-native-smartassets
This project is based on react-native-smartassets.
This third-party library has been migrated to GitCode and is now available for direct download from npm, the new package name is: @react-native-ohos/react-native-smartassets, the version correspondence details are as follows:
| Name | Version(Npm Address) | Release Information | Supported RN Version | Supported Autolink | Compile API Version | Community Baseline Version | Source code address |
|---|---|---|---|---|---|---|---|
| @react-native-ohos/react-native-smartassets | ~1.0.6 | GitCode Releases | 0.72./0.82. | Partially(>=1.0.7) | API12+ | 1.0.4 | master |
| @react-native-oh-tpl/react-native-smartassets | <=1.0.5@deprecated | Github Releases(deprecated) | 0.72.* | No | API12+ | 1.0.4 | sig |
Introduction
SmartAssets is a third-party library that smartly loads React Native image resources. It supports locating and loading image assets from both the apk (ipa) package directory and the jsbundle directory. It correctly resolves image paths in multi-bundle and dynamic asset delivery scenarios, reducing the application package size and improving asset loading efficiency.
Installation
Go to the project directory and execute the following instruction:
npm
npm install @react-native-ohos/react-native-smartassets
yarn
yarn add @react-native-ohos/react-native-smartassets
Link
| Version | Supported Autolink | Supported RN Version |
|---|---|---|
| ~1.0.6 | Partially(>=1.0.7) | 0.72./0.82. |
Projects using AutoLink need to be configured according to this document, AutoLink framework guide: https://gitcode.com/CPF-RN/ohos_react_native/blob/main/docs/en/02-development/02-development-guide/autolinking.md
If the version you are using supports Autolink and the project has integrated Autolink, you can skip the ManualLink configuration.
ManualLink: This step provides guidance for manually configuring native dependencies.
Open the harmony directory of the HarmonyOS project in DevEco Studio.
1. Overrides RN SDK
To ensure the project relies on the same version of the RN SDK, you need to add an overrides field in the project's root oh-package.json5 file, specifying the RN SDK version to be used. The replacement version can be a specific version number, a semver range, or a locally available HAR package or source directory.
For more information about the purpose of this field, please refer to the official documentation.
{
"overrides": {
"@rnoh/react-native-openharmony": "~0.72.38" // ohpm version
// "@rnoh/react-native-openharmony" : "./react_native_openharmony.har" // a locally available HAR package
// "@rnoh/react-native-openharmony" : "./react_native_openharmony" // source code directory
}
}
2. Introducing Native Code
Currently, two methods are available:
- Use the HAR file.
- Directly link to the source code.
Method 1 (recommended): Use the HAR file.
The HAR file is stored in the `harmony` directory in the installation path of the third-party library.
Open entry/oh-package.json5 file and add the following dependencies:
"dependencies": {
"@rnoh/react-native-openharmony": "file:../react_native_openharmony",
"@react-native-ohos/react-native-smartassets": "file:../../node_modules/@react-native-ohos/react-native-smartassets/harmony/smartassets.har"
}
Click the sync button in the upper right corner.
Alternatively, run the following instruction on the terminal:
cd entry
ohpm install
Method 2: Directly link to the source code.
For details, see [Directly Linking Source Code](https://gitcode.com/CPF-RN/usage-docs/blob/master/en/link-source-code.md).
3. Configuring CMakeLists and Introducing SmartAssetsPackage
Open entry/src/main/cpp/CMakeLists.txt and add the following code:
project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../react-native-harmony/harmony/cpp")
set(LOG_VERBOSITY_LEVEL 1)
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_compile_definitions(WITH_HITRACE_SYSTRACE)
add_subdirectory("${RNOH_CPP_DIR}" ./rn)
# RNOH_BEGIN: manual_package_linking_1
add_subdirectory("../../../../sample_package/src/main/cpp" ./sample-package)
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-smartassets/src/main/cpp" ./smartassets)
# RNOH_END: manual_package_linking_1
file(GLOB GENERATED_CPP_FILES "./generated/*.cpp")
add_library(rnoh_app SHARED
${GENERATED_CPP_FILES}
"./PackageProvider.cpp"
"${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)
target_link_libraries(rnoh_app PUBLIC rnoh)
# RNOH_BEGIN: manual_package_linking_2
target_link_libraries(rnoh_app PUBLIC rnoh_sample_package)
+ target_link_libraries(rnoh_app PUBLIC smartassets)
# RNOH_END: manual_package_linking_2
Open entry/src/main/cpp/PackageProvider.cpp and add the following code:
#include "RNOH/PackageProvider.h"
#include "generated/RNOHGeneratedPackage.h"
+ #include "SmartAssetsPackage.h"
using namespace rnoh;
std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
return {
std::make_shared<RNOHGeneratedPackage>(ctx),
+ std::make_shared<SmartAssetsPackage>(ctx)
};
}
4. Introducing SmartAssetsPackage to ArkTS
Open entry/src/main/ets/RNPackagesFactory.ets and add:
...
+ import { SmartAssetsPackage } from '@react-native-ohos/react-native-smartassets';
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
return [
+ new SmartAssetsPackage(ctx)
];
}
Running
Click the sync button in the upper right corner.
Alternatively, run the following instruction on the terminal:
cd entry
ohpm install
Then build and run the code.
Constraints
Compatibility
This document is verified based on the following versions:
- RNOH: 0.72.32; SDK: HarmonyOS-Next-DB6 5.0.0.61; IDE: DevEco Studio 5.0.3.706; ROM: 3.0.0.61;
- RNOH: 0.82.1; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;
Permission Requirements
- The HarmonyOS module of this library declares the network permission. To load image resources over the network, configure the following in
entry/src/main/module.json5:
requestPermissions: [
{
name: "ohos.permission.INTERNET",
},
],
Example
The following code shows the basic use scenario of the repository:
The package name used in the import statement is @react-native-ohos/react-native-smartassets.
import React, { useEffect } from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
import { SmartAssets } from '@react-native-ohos/react-native-smartassets';
const App = () => {
useEffect(() => {
// Initialize SmartAssets to install the image asset resolving hook
SmartAssets.initSmartAssets();
// Specify the bundle path to locate image assets (optional)
SmartAssets.setBundlePath('/data/storage/el2/base/haps/entry/files/bundle');
return () => {
// Clear the bundle path setting when the component unmounts
SmartAssets.setBundlePath();
};
}, []);
return (
<View style={styles.container}>
{/* Use the Image component as usual, SmartAssets handles asset loading automatically */}
<Image
source={require('./assets/images/demo.png')}
style={styles.image}
resizeMode="contain"
/>
<Text style={styles.label}>Network image</Text>
<Image
source={{ uri: 'https://picsum.photos/200/200' }}
style={styles.image}
resizeMode="contain"
/>
</View>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
image: {
width: 100,
height: 100,
marginBottom: 10,
},
label: {
fontSize: 12,
color: '#666',
marginBottom: 5,
},
});
How to Use
Initialization Mode
Call SmartAssets.initSmartAssets() at the application entry or on page mount to install the image asset resolution hook (duplicate calls are safely ignored internally). After initialization, local image resources loaded by the Image component via require() are automatically resolved by SmartAssets, so no per-image source changes are required in business code.
import React, { useEffect, useState } from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
import { SmartAssets } from '@react-native-ohos/react-native-smartassets';
const InitDemo = () => {
const [resolvedUri, setResolvedUri] = useState('');
useEffect(() => {
// Initialize SmartAssets and install the image asset resolution hook
SmartAssets.initSmartAssets();
// After loading a local image via require, resolveAssetSource shows the resolved uri
const source = require('../assets/avatar.png');
setResolvedUri(Image.resolveAssetSource(source)?.uri ?? '');
}, []);
return (
<View style={styles.container}>
<Text style={styles.label}>{resolvedUri}</Text>
<Image
source={require('../assets/avatar.png')}
style={styles.image}
resizeMode="contain"
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
alignItems: 'center',
padding: 15,
},
image: {
width: 100,
height: 100,
marginBottom: 10,
},
label: {
fontSize: 10,
color: '#666',
marginBottom: 5,
textAlign: 'center',
},
});
Custom Bundle Path Mode
When image resources are located in a custom bundle directory (for example, a dynamically delivered resource package), call SmartAssets.setBundlePath(path) to specify the lookup path; calling it without arguments clears the configured path, which is recommended on component unmount.
useEffect(() => {
SmartAssets.initSmartAssets();
// Specify a custom bundle directory for image asset lookup
SmartAssets.setBundlePath('/data/storage/el2/base/haps/entry/files/bundle');
return () => {
// Clear the bundle path setting on component unmount
SmartAssets.setBundlePath();
};
}, []);
Available APIs
The **Platform** column indicates the platform where the properties are supported in the original third-party library.
If the value of **OpenHarmony Platform Support** is **yes**, it means that the OpenHarmony platform supports this property; **no** means the opposite; **partially** means some capabilities of this property are supported. The usage method is the same on different platforms and the effect is the same as that of iOS or Android.
API
| Name | Type | Parameter Type | Return Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
| initSmartAssets() | function | / | void | yes | iOS/Android | Yes | Initializes SmartAssets and installs the image asset loading hook. |
| initSmartAssetsInner() | function | / | void | no | iOS/Android | Yes | Internal initialization logic that installs the asset resolving hook, called by initSmartAssets internally. |
| setBundlePath(bundlePath: string) | function | string | void | no | iOS/Android | Yes | Specifies the bundle path to locate image assets. Passing no argument clears the configured path. |
| setiOSRelateMainBundlePath(relatePath: string) | function | string | void | no | iOS | No | Sets the iOS path relative to the main bundle to locate image assets. Only supported on iOS. |
Known Issues
None
Other
- The
setiOSRelateMainBundlePathmethod only supports the iOS platform in the original third-party library, so it is not supported on the HarmonyOS platform.
Directory Structure
/rntpc_react-native-smartassets # Project root directory
│ buildEnv.sh
│ CHANGELOG.md
│ index.js # JS API entry
│ LICENSE
│ OAT.xml
│ package.json
│ README.md # Chinese document
│ README_en.md # English document
│
├─example # Example project
│
├─harmony
│ │ smartassets.har # Compiled HAR package (HarmonyOS Archive)
│ │
│ └─smartassets # HarmonyOS adaptation core code
│ │ build-profile.json5
│ │ BuildProfile.ets
│ │ consumer-rules.txt
│ │ hvigorfile.ts
│ │ index.ets # HarmonyOS adaptation code entry
│ │ obfuscation-rules.txt
│ │ oh-package-lock.json5
│ │ oh-package.json5
│ │ ts.ets
│ │
│ └─src
│ └─main
│ ├─cpp # C++ code
│ │ │ CMakeLists.txt
│ │ │ SmartAssetsPackage.h
│ │ │
│ │ └─generated # C++ code generated by codegen
│ │
│ ├─ets # ArkTS business layer
│ │ │ SmartAssetsModule.ets # Native TurboModule implementation
│ │ │ SmartAssetsPackage.ets # Native package registration
│ │ │
│ │ └─generated # ArkTS code generated by codegen
│ │
│ ├─module.json5
│ └─resources # Resource files
│
└─src # JS implementation
NativeSmartAssets.ts # TurboModule JS declaration
How to Contribute
If you find any problem when using react-native-smartassets, submit an issue or a PR.
License
This project is licensed under The MIT License (MIT).