使用rnpm

时间:2017-10-17 10:08:16

标签: react-native assets react-native-cli

有很多关于使用rnpm包含字体资源的教程。这些是步骤:

  1. 将字体放入,例如./assets/fonts
  2. 将以下代码段添加到package.json:

    "rnpm": {
      "assets": [
        "./assets/fonts",
      ]
    }
    
  3. 运行react-native link

  4. 适用于字体资源,但其他类型呢?我需要包含一个文本文件,但重复上述文本文件资产的步骤似乎没有任何影响。我错过了什么?互联网上没有提及,所以我甚至不确定rnpm是否可行。

    编辑:更具体地说,我在file.txt目录中添加了./assets/raw,并在./assets/raw ./assets/fonts旁边添加了rnpm在package.json中配置。运行react-native link后我希望file.txt出现在Android项目资产目录(/android/app/src/main/assets)中,以及"复制捆绑资源"在iOS项目中构建阶段,但它没有发生。 react-native link正常运行并且没有产生任何错误。

    我的最终目标是在应用程序包中包含一个文本文件,并在运行时将其访问。另一种选择是用JSON包装文本,但是这样它最终会在JS包中增加大约25%,这可能不太好。有些人还建议您react-native-fs阅读该文件,但我不确定将其放在哪里,以便Android和iOS都可以使用。 rnpm知道在哪里放置Android和iOS的资产(以及如何将它们复制到捆绑包),所以使用它似乎是要走的路,但我不能使它适用于文本资产。

    有任何想法或建议吗?

1 个答案:

答案 0 :(得分:0)

在React Native CLI中挖掘后,我发现react-native link只处理字体。以下是/node_modules/react-native/local-cli/link/android/copyAssets.js的相关代码:

/**
 * Copies each file from an array of assets provided to targetPath directory
 *
 * For now, the only types of files that are handled are:
 * - Fonts (otf, ttf) - copied to targetPath/fonts under original name
 */
module.exports = function copyAssetsAndroid(files, targetPath) {
  const assets = groupFilesByType(files);

  (assets.font || []).forEach(asset =>
    fs.copySync(asset, path.join(targetPath, 'fonts', path.basename(asset)))
  );
};

如您所见,groupFilesByType按照MIME类型(字体,文本等)对所有文件进行分组,但实际上只将字体复制到项目中。

其他人之前遇到过这个问题。有a pull request添加了对视频资产的支持,但它没有合并。显然,要走的路是使用打包机。