You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Expo版React Native中输出文件名称列表?

在Expo版React Native中获取assets文件夹图片文件名列表的方案

因为Expo项目无法直接使用react-native-fs这类原生模块,所以需要采用兼容Expo的方案,以下是几种可行方式:

方案一:预先生成静态文件名列表(推荐)

通过Node.js脚本遍历assets文件夹,生成包含所有图片文件名的JSON文件,再在React Native代码中导入使用,这是最稳定的方案。

  1. 项目根目录创建脚本文件generate-asset-list.js:
const fs = require('fs');
const path = require('path');

// 目标assets文件夹路径
const assetsDir = path.join(__dirname, 'assets');
// 要识别的图片后缀
const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp'];

// 递归遍历文件夹获取图片文件
const getImageFiles = (dir) => {
  let files = [];
  const items = fs.readdirSync(dir, { withFileTypes: true });
  
  for (const item of items) {
    const itemPath = path.join(dir, item.name);
    if (item.isDirectory()) {
      files = [...files, ...getImageFiles(itemPath)];
    } else {
      const ext = path.extname(item.name).toLowerCase();
      if (imageExtensions.includes(ext)) {
        // 保存相对assets文件夹的路径,也可只保存文件名
        files.push(path.relative(assetsDir, itemPath));
      }
    }
  }
  return files;
};

// 生成并保存JSON文件
const imageFiles = getImageFiles(assetsDir);
fs.writeFileSync(
  path.join(__dirname, 'asset-list.json'),
  JSON.stringify(imageFiles, null, 2)
);
  1. 在package.json中添加执行脚本:
"scripts": {
  "generate-assets": "node generate-asset-list.js"
}
  1. 每次新增图片后,运行npm run generate-assets更新列表,然后在React Native代码中导入使用:
import assetList from './asset-list.json';

// 输出所有图片文件名/路径
console.log('assets图片列表:', assetList);

方案二:动态导入(适用于命名有规律的图片)

如果你的图片命名有固定规则(如image1.png、image2.png),可以通过循环动态生成require路径:

import { Asset } from 'expo-asset';

const getImageAssets = async () => {
  const assetList = [];
  // 假设图片是image1到image10
  for (let i = 1; i <= 10; i++) {
    try {
      const asset = Asset.fromModule(require(`./assets/image${i}.png`));
      await asset.downloadAsync();
      assetList.push({
        name: `image${i}.png`,
        uri: asset.localUri
      });
    } catch (e) {
      console.log(`图片image${i}.png不存在`);
    }
  }
  return assetList;
};

// 调用获取列表
getImageAssets().then(list => console.log('图片列表:', list));

方案三:使用Expo FileSystem(局限性大)

Expo的FileSystem可以访问打包后的bundle资源,但需要提前知道文件名,适合验证单个文件是否存在:

import * as FileSystem from 'expo-file-system';

const checkAssetExists = async (fileName) => {
  const assetUri = FileSystem.bundleDirectory + fileName;
  const info = await FileSystem.getInfoAsync(assetUri);
  return info.exists;
};

// 示例:检查logo.png是否存在
checkAssetExists('logo.png').then(exists => console.log('文件是否存在:', exists));

内容的提问来源于stack exchange,提问作者hotgatorade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:15:51