React-native:下载并解压大型语言文件

stk*_*flw 5 react-native

一个多语言的本机应用程序。每个语言包约为 50MB。将所有这些都包含在一个包中是没有意义的。那么,我该怎么办呢?

我认为正确的方法是在选择语言时下载相应的语言文件。接下来我该怎么办?我想使用 AsyncStorage 还是什么来存储它?

May*_*ita 7

简要说明,您将:

  1. 将 JSON 以 ZIP 格式存储在 Google Storage 中(节省内存/带宽/时间)

  2. 将文件解压缩为 JSON(在 RN 中)

  3. 将 JSON 存储在 AsyncStorage 中(在 RN 中)

  4. 从 AsyncStorage 中检索(在 RN 中)

[依赖项摘要]您可以使用这些依赖项执行此操作:

提示:始终以 zip 格式存储大语言 json(这最多可以节省 90% 的大小)。

我在这里做了一个快速测试:一个 3.52MB 的 json 文件,结果是一个 26KB 的压缩文件!

让我们考虑一下您存储的 zip 文件,可以使用公共 url 访问,例如:https://storage.googleapis.com/bucket/folder/lang-file.zip。

安装并链接所有上述 RN deps,这是使其正常工作所必需的。

导入 deps

import RNFetchBlob from 'rn-fetch-blob';
import { unzip } from 'react-native-zip-archive';
import AsyncStorage from '@react-native-community/async-storage';
Run Code Online (Sandbox Code Playgroud)
  1. 使用 下载文件rn-fetch-blob。这可以使用:
RNFetchBlob
.config({
  // add this option that makes response data to be stored as a file,
  // this is much more performant.
  fileCache : true,
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
  //some headers ..
})
.then((res) => {
  // the temp file path
  console.log('The file saved to ', res.path())

  // Unzip will be called here!
  unzipDownloadFile(res.path(), (jsonFilePath) => {

    // Let's store this json.
    storeJSONtoAsyncStorage(jsonFilePath);

    // Done!
    // Now you can read the AsyncStorage everytime you need (using function bellow).
  });
});
Run Code Online (Sandbox Code Playgroud)
  1. [功能] 解压下载的文件,使用react-native-zip-archive:
function unzipDownloadFile(target, cb) {
  const targetPath = target;
  const sourcePath = `${target}.json`;
  const charset = 'UTF-8';

  unzip(sourcePath, targetPath, charset)
  .then((path) => {
    console.log(`unzip completed at ${path}`)

    return cb(path);
  })
  .catch((error) => {
    console.error(error)
  });
}
Run Code Online (Sandbox Code Playgroud)
  1. [功能] 在 AsyncStorage 中存储 JSON:
function storeJSONtoAsyncStorage (path) {
  RNFetchBlob.fs.readFile(path, 'utf-8')
  .then((data) => {
    AsyncStorage.setItem('myJSON', data);
  });
}
Run Code Online (Sandbox Code Playgroud)
  1. 从 AsyncStorage 检索 JSON 数据(随时):
AsyncStorage.getItem('myJSON', (err, json) => {
  if (err) {
    console.log(err);
  } else {
    const myJSON = JSON.parse(json);

    // ... do what you need with you json lang file here...
  }
})
Run Code Online (Sandbox Code Playgroud)

这足以让动态 json lang 文件在 React Native 中工作。

我正在使用这种方法为我的 i18n'ed 项目提供类似的功能。


小智 0

是的,您让翻译文件可下载是正确的。

您可以将下载的文件存储在应用程序的文档目录中。
之后,您可以使用包来加载翻译。例如 https://github.com/fnando/i18n-js。