Expo 资源

通用库,允许下载资源并将其与其他库一起使用。

Android
iOS
tvOS
Web
Included in Expo Go
Bundled version:
~12.0.12

expo-asset 提供了一个与 Expo 资源系统的接口。资源是指在应用源代码旁边存放的、在运行时应用需要的任何文件。示例包括图片、字体和音效。Expo 的资源系统与 React Native 的系统集成,因此你可以使用 require('path/to/file') 来引用文件。例如,这就是在 React Native 中如何引用静态图片文件用于 Image 组件的方式。更多信息请查看 React Native 的静态图片资源文档。这种引用静态图片资源的方法在 Expo 中可以开箱即用。

安装

🌐 Installation

Terminal
npx expo install expo-asset

If you are installing this in an existing React Native app, make sure to install expo in your project.

应用配置中的配置

🌐 Configuration in app config

如果你在项目中使用配置插件(连续原生生成 (CNG)),可以使用其内置的 配置插件 来配置 expo-asset。该插件允许你配置无法在运行时设置并且需要构建新的应用二进制文件才能生效的各种属性。如果你的应用使用 CNG,那么你需要手动配置该库。

🌐 You can configure expo-asset using its built-in config plugin if you use config plugins in your project (Continuous Native Generation (CNG)). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect. If your app does not use CNG, then you'll need to manually configure the library.

Example app.json with config plugin

app.json
{ "expo": { "plugins": [ [ "expo-asset", { "assets": ["path/to/file.png", "path/to/directory"] } ] ] } }

Configurable properties

NameDefaultDescription
assets[]

一个要链接到原生项目的资源文件或目录数组。路径应相对于项目根目录,这样文件名,无论是直接指定还是使用目录,都会成为资源名称。

支持的文件类型:

  • 图片:.png.jpg.gif
  • 媒体:.mp4.mp3.lottie.riv
  • SQLite 数据库文件:.db

注意:要导入现有的数据库文件 (.db),请参阅 SQLite API 参考 中的说明。对于其他文件类型(如 .lottie.riv),请参阅 如何在 metro 配置中为 assetExts 添加文件扩展名

用法

🌐 Usage

了解更多关于如何使用 expo-asset 配置插件在项目中嵌入资源文件的信息,请参阅 在构建时加载资源

🌐 Learn more about how to use the expo-asset config plugin to embed an asset file in your project in Load an asset at build time.

应用接口

🌐 API

import { Asset } from 'expo-asset';

Hooks

useAssets(moduleIds)

Android
iOS
tvOS
Web
ParameterType
moduleIdsnumber | number[]

Downloads and stores one or more assets locally. After the assets are loaded, this hook returns a list of asset instances. If something went wrong when loading the assets, an error is returned.

Note, the assets are not "reloaded" when you dynamically change the asset list.

Returns:
[Asset[] | undefined, Error | undefined]

Returns an array containing:

  • on the first position, a list of all loaded assets. If they aren't loaded yet, this value is undefined.
  • on the second position, an error which encountered when loading the assets. If there was no error, this value is undefined.

Example

const [assets, error] = useAssets([require('path/to/asset.jpg'), require('path/to/other.png')]); return assets ? <Image source={assets[0]} /> : null;

Classes

Asset

Android
iOS
tvOS
Web

The Asset class represents an asset in your app. It gives metadata about the asset (such as its name and type) and provides facilities to load the asset data.

Asset Properties

downloaded

Android
iOS
tvOS
Web
Type: boolean • Default: false

Whether the asset has finished downloading from a call to downloadAsync().

hash

Android
iOS
tvOS
Web
Read Only • Literal type: union • Default: null

The MD5 hash of the asset's data.

Acceptable values are: null | string

height

Android
iOS
tvOS
Web
Literal type: union • Default: null

If the asset is an image, the height of the image data divided by the scale factor. The scale factor is the number after @ in the filename, or 1 if not present.

Acceptable values are: null | number

localUri

Android
iOS
tvOS
Web
Literal type: union • Default: null

If the asset has been downloaded (by calling downloadAsync()), the file:// URI pointing to the local file on the device that contains the asset data.

Acceptable values are: null | string

name

Android
iOS
tvOS
Web
Type: string

The name of the asset file without the extension. Also without the part from @ onward in the filename (used to specify scale factor for images).

type

Android
iOS
tvOS
Web
Read Only • Type: string

The extension of the asset filename.

uri

Android
iOS
tvOS
Web
Read Only • Type: string

A URI that points to the asset's data on the remote server. When running the published version of your app, this refers to the location on Expo's asset server where Expo has stored your asset. When running the app from Expo CLI during development, this URI points to Expo CLI's server running on your computer and the asset is served directly from your computer. If you are not using Classic Updates (legacy), this field should be ignored as we ensure your assets are on device before running your application logic.

width

Android
iOS
tvOS
Web
Literal type: union • Default: null

If the asset is an image, the width of the image data divided by the scale factor. The scale factor is the number after @ in the filename, or 1 if not present.

Acceptable values are: null | number

Asset Methods

downloadAsync()

Android
iOS
tvOS
Web

Downloads the asset data to a local file in the device's cache directory. Once the returned promise is fulfilled without error, the localUri field of this asset points to a local file containing the asset data. The asset is only downloaded if an up-to-date local file for the asset isn't already present due to an earlier download. The downloaded Asset will be returned when the promise is resolved.

Note: There is no guarantee that files downloaded via downloadAsync persist between app sessions. downloadAsync stores files in the caches directory, so it's up to the OS to clear this folder at its own discretion or when the user manually purges the caches directory. Downloaded assets are stored as ExponentAsset-{cacheFileId}.{extension} within the cache directory. To manually clear cached assets, you can use expo-file-system to delete the cache directory: Paths.cache.delete() or use the legacy API deleteAsync(cacheDirectory).

Returns:
Promise<Asset>

Returns a Promise which fulfills with an Asset instance.

fromMetadata(meta)

Android
iOS
tvOS
Web
ParameterType
metaAssetMetadata

Returns:
Asset

fromModule(virtualAssetModule)

Android
iOS
tvOS
Web
ParameterTypeDescription
virtualAssetModulestring | number | { height: number, uri: string, width: number }

The value of require('path/to/file') for the asset or external network URL


Returns the Asset instance representing an asset given its module or URL.

Returns:
Asset

The Asset instance for the asset.

fromURI(uri)

Android
iOS
tvOS
Web
ParameterType
uristring

Returns:
Asset

loadAsync(moduleId)

Android
iOS
tvOS
Web
ParameterTypeDescription
moduleIdstring | number | number[] | string[]

An array of require('path/to/file') or external network URLs. Can also be just one module or URL without an Array.


A helper that wraps Asset.fromModule(module).downloadAsync for convenience.

Returns:
Promise<Asset[]>

Returns a Promise that fulfills with an array of Assets when the asset(s) has been saved to disk.

Example

const [{ localUri }] = await Asset.loadAsync(require('./assets/snack-icon.png'));

Types

AssetDescriptor

Android
iOS
tvOS
Web
PropertyTypeDescription
hash(optional)string | null
-
height(optional)number | null
-
namestring
-
typestring
-
uristring
-
width(optional)number | null
-

AssetMetadata

Android
iOS
tvOS
Web

Type: Pick<PackagerAsset, 'httpServerLocation' | 'name' | 'hash' | 'type' | 'scales' | 'width' | 'height'> extended by:

PropertyTypeDescription
fileHashes(optional)string[]
-
fileUris(optional)string[]
-
uri(optional)string
-