使用自定义扩展加载资产不起作用

sbq*_*bqq 7 reactjs react-native expo

我正在尝试在 react-native 中实现我的第一个应用程序,我需要从保存在我的项目文件夹中的静态文件中打开数据库。

我读到我需要允许从资产加载自定义扩展文件,所以我将以下片段添加到我的app.json文件中:

"packagerOpts": {
    "assetExts": ["sqlite", "db"]
},
Run Code Online (Sandbox Code Playgroud)

接下来,我尝试在我的 App.js 组件中使用 .sqlite 或 .db 扩展名导入这个静态文件componentDidMount()

componentDidMount = async () => {
  await Expo.FileSystem.downloadAsync(
    Expo.Asset.fromModule(require("./assets/db/local.db")).uri,
    `${Expo.FileSystem.documentDirectory}SQLite/local.db`
  );

  SQLite.openDatabase("local.db");
};
Run Code Online (Sandbox Code Playgroud)

但世博会建设者一直在说Unable to resolve "./assets/db/local.db" from "App.js"。请问有什么建议吗?

小智 8

以下代码来自上面的2个答案

在项目根目录创建metro.config.js

const defaultAssetExts = require("metro-config/src/defaults/defaults").assetExts;

module.exports = {
  resolver: {
    assetExts: [
      ...defaultAssetExts,
      // 3D Model formats
      "dae",
      "obj",
      "mtl",
      // sqlite format
      "db",
      "sqlite"
    ]
  }
};
Run Code Online (Sandbox Code Playgroud)

可选择安装metro-dependency: npm i metro-config --save-dev


sbq*_*bqq 2

我发现世博会存在某种错误,但有针对此问题提出/批准了公关。对于那些迫不及待地等待官方错误修复的人来说,还有一个解决方法:

使用 assetExts 创建一个 Metro.config.js 文件解决了我的问题:

module.exports = {
  resolver: {
    assetExts: ["db", "mp3", "ttf"]
  }
}
Run Code Online (Sandbox Code Playgroud)

并导入这个文件让我们说在你的App.js中?我现在可以从文件打开 SQLite 数据库。