美文网首页
React-Native中metro缓存地址

React-Native中metro缓存地址

作者: 涅槃快乐是金 | 来源:发表于2022-09-30 18:14 被阅读0次

    react-native在使用metro构建时为了提升构建效率采用了缓存机制,虽然在打包时有效地提升了打包速度,但是在进行问题排查时虽然修改了JS代码,但是由于优先使用了缓存,会造成变更后的代码一直无法生效。

    设置缓存

    由于构建打包采用的是metro,通过resetCache = true,进行清除缓存

    // metro.config.js
    module.exports = {
      resetCache:true,     // 增加这一行
      ...
    }
    

    resetCache=true的作用是每次构建时均清空缓存,其默认是false,可以加快构建速度。
    但是在某些情况下会出现因缓存导致的问题。

    缓存地址

    虽然我们通过设置不使用缓存可以有效的避免缓存问题,但是技术人员需要找到具体的缓存地址,通过merto的代码进行寻根
    当配置了resetCache:true,,构建是会新增一行打印输出:the transform cache was reset.;
    我们可以在/metro/src/lib/TerminalReporter.js,找到相关代码:

    // metro/src/lib/TerminalReporter.js 236行
    case "transform_cache_reset":
            reporting.logWarning(this.terminal, "the transform cache was reset.");
            break;
    

    再通过transform_cache_reset这个事件,我们可以找到这个时间发出的地方:

    //metro/src/Server.js 85行
    if (this._config.resetCache) {
          this._config.cacheStores.forEach((store) => store.clear());
    
          this._config.reporter.update({
            type: "transform_cache_reset",
          });
        }
    

    在metro/src/Server中判断是否要清除缓存,如果是true就执行clear;
    通过cacheStores,我们可以找到初始化的内容

    //metro-config/src/defaults/index.js 135行
      cacheStores: [
        new FileStore({
          root: path.join(os.tmpdir(), "metro-cache"),
        }),
      ],
    

    可以看到,缓存地址用的系统缓存,我们可以执行下os.tmpdir()找到对应的系统缓存的文件夹

    //test.js
    const os = require("os");
    console.log(os.tmpdir())
    
    $ node test.js
    /var/folders/99/4rdd525x7_q_3fq14qrwvwsd54l1nm/T
    

    打开这个文件可以看到有很多的缓存文件,我们要找的metro的构建缓存就在metro-cache

    相关文章

      网友评论

          本文标题:React-Native中metro缓存地址

          本文链接:https://www.haomeiwen.com/subject/rtcrartx.html