”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 帮助 React Native 开发者的脚本

帮助 React Native 开发者的脚本

发布于2024-11-01
浏览:830

A Script To Help React Native Developers

你好呀!

如果您一直在使用 React Native,您可能遇到过模拟器问题。您运行 React Native 命令,但未检测到模拟器。即使在 .zshrc、.bash_profile 或类似文件中设置了所有必要的环境变量后,它仍然无法工作。

以下是一些常见问题和修复:

  1. 找不到模拟器:如果 Android SDK 路径设置不正确,可能会发生这种情况。仔细检查 ANDROID_HOME 和 PATH 环境变量是否指向正确的目录。您可以将这些行添加到 .zshrc 或 .bash_profile:

    export ANDROID_HOME=$HOME/Library/Android/sdk
    export PATH=$PATH:$ANDROID_HOME/emulator
    export PATH=$PATH:$ANDROID_HOME/tools
    export PATH=$PATH:$ANDROID_HOME/tools/bin
    export PATH=$PATH:$ANDROID_HOME/platform-tools
    

    进行这些更改后,重新启动终端或运行 source ~/.zshrc (或 source ~/.bash_profile)。

  2. Watchman 错误:有时,Watchman(Facebook 的文件监视服务)可能会导致陈旧文件缓存出现问题。要解决此问题,请运行:

    watchman watch-del-all
    

    然后,重新启动 React Native 服务器。

  3. adb 反向连接到 localhost:如果您的应用程序无法从 Android 模拟器内连接到 localhost,您可能需要运行:

    adb reverse tcp:8081 tcp:8081
    

    此命令将流量从模拟器路由到本地计算机。确保可以从您的终端访问 adb。

  4. 清除缓存并重建:如果您仍然遇到问题,请尝试清除缓存并重建项目:

    npm start -- --reset-cache
    cd android && ./gradlew clean
    cd ios && xcodebuild clean
    

    然后再次运行您的 React Native 应用程序。

  5. 直接使用react-native run-android 或 run-ios:如果模拟器无法从 IDE 或终端正确启动,请尝试直接使用以下命令运行应用程序:

    npx react-native run-android
    npx react-native run-ios
    

调试这些问题可能会令人沮丧,但这些步骤帮助我解决了许多常见问题。

我也创建了一个易于使用的脚本

const {spawn, exec} = require('child_process');
const path = require('path');

// Define paths
const projectPath = path.resolve();

// Define commands
const watchDelCommand = `watchman watch-del '${projectPath}'`;
const watchProjectCommand = `watchman watch-project '${projectPath}'`;

// Function to execute commands
const clearWatchman = () => {
  // Execute watch-del command
  exec(watchDelCommand, (error, stdout, stderr) => {
    if (error) {
      console.error(`Error executing watch-del command: ${error.message}`);
      return;
    }
    if (stderr) {
      console.error(`stderr: ${stderr}`);
      return;
    }
    console.log(`watch-del command executed successfully: ${stdout}`);

    // Execute watch-project command
    exec(watchProjectCommand, (error, stdout, stderr) => {
      if (error) {
        console.error(
          `Error executing watch-project command: ${error.message}`,
        );
        return;
      }
      if (stderr) {
        console.error(`stderr: ${stderr}`);
        return;
      }
      console.log(`watch-project command executed successfully: ${stdout}`);
    });
  });
};

async function reverseAdb() {
  console.log('Running... adb reverse tcp:8080 tcp:8080');
  // After the emulator has started  adb reverse tcp:8080 tcp:8080
  const adbReverse = spawn('adb', ['reverse', 'tcp:8080', 'tcp:8080']);
  await new Promise((resolve, reject) => {
    let output = '';
    adbReverse.stdout.on('data', data => {
      output  = data.toString();
    });
    adbReverse.on('close', () => {
      resolve();
    });
    adbReverse.stderr.on('error', reject);
  }).catch(error => console.error('Error  reversing ADB port to 8080:', error));
}

async function runEmulator() {
  try {
    clearWatchman();
    // Check for running emulator
    const adbDevices = spawn('adb', ['devices']);
    const devices = await new Promise((resolve, reject) => {
      let output = '';
      adbDevices.stdout.on('data', data => {
        output  = data.toString();
      });
      adbDevices.on('close', () => {
        resolve(output.includes('emulator'));
      });
      adbDevices.stderr.on('error', reject);
    });

    if (devices) {
      console.log('Emulator is already running');
      reverseAdb();
      return;
    }

    // Get list of available emulators
    const emulatorList = spawn('emulator', ['-list-avds']);
    const emulatorName = await new Promise((resolve, reject) => {
      let output = '';
      emulatorList.stdout.on('data', data => {
        output  = data.toString();
      });
      emulatorList.on('close', () => {
        const lines = output.split('\n').filter(Boolean); // Filter out empty lines
        if (lines.length === 0) {
          reject(new Error('No AVDs found'));
        } else {
          resolve(lines[lines.length - 1]); // Get the last non-empty line
        }
      });
      emulatorList.stderr.on('error', reject);
    });

    // Start the emulator in detached mode
    const emulatorProcess = spawn('emulator', ['-avd', emulatorName], {
      detached: true,
      stdio: 'ignore',
    });

    emulatorProcess.unref(); // Allow the parent process to exit independently of the child

    reverseAdb();

    console.log(`Starting emulator: ${emulatorName}`);
  } catch (error) {
    console.error('Error running emulator:', error);
  }
}

runEmulator();


// package.json

  "scripts": {
    ...

    "dev:android": "yarn android:emulator && npx react-native@latest start",
    "android:emulator": "node runEmulator.js",

    ...
  },

通过使用上面的脚本,您可以同时运行模拟器和React Native。

感谢您的阅读!

版本声明 本文转载于:https://dev.to/frulow/a-script-to-help-react-native-developers-fk7?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    网格超过身体,用100%grid-template-columns 为什么在grid-template-colms中具有100%的显示器,当位置设置为设置的位置时,grid-template-colly修复了?问题: 考虑以下CSS和html: class =“ snippet-code”> g...
    编程 发布于2025-03-12
  • 如何使用Regex在PHP中有效地提取括号内的文本
    如何使用Regex在PHP中有效地提取括号内的文本
    php:在括号内提取文本在处理括号内的文本时,找到最有效的解决方案是必不可少的。一种方法是利用PHP的字符串操作函数,如下所示: 作为替代 $ text ='忽略除此之外的一切(text)'; preg_match('#((。 &&& [Regex使用模式来搜索特...
    编程 发布于2025-03-12
  • 如何使用PHP将斑点(图像)正确插入MySQL?
    如何使用PHP将斑点(图像)正确插入MySQL?
    essue VALUES('$this->image_id','file_get_contents($tmp_image)')";This code builds a string in PHP, but the function call ...
    编程 发布于2025-03-12
  • 对象拟合:IE和Edge中的封面失败,如何修复?
    对象拟合:IE和Edge中的封面失败,如何修复?
    To resolve this issue, we employ a clever CSS solution that solves the problem:position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%)...
    编程 发布于2025-03-12
  • 如何限制动态大小的父元素中元素的滚动范围?
    如何限制动态大小的父元素中元素的滚动范围?
    在交互式接口中实现垂直滚动元素的CSS高度限制问题:考虑一个布局,其中我们具有与用户垂直滚动一起移动的可滚动地图div,同时与固定的固定sidebar保持一致。但是,地图的滚动无限期扩展,超过了视口的高度,阻止用户访问页面页脚。$("#map").css({ marginT...
    编程 发布于2025-03-12
  • 如何使用FormData()处理多个文件上传?
    如何使用FormData()处理多个文件上传?
    )处理多个文件输入时,通常需要处理多个文件上传时,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    编程 发布于2025-03-12
  • HTML格式标签
    HTML格式标签
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    编程 发布于2025-03-12
  • 如何在JavaScript对象中动态设置键?
    如何在JavaScript对象中动态设置键?
    在尝试为JavaScript对象创建动态键时,如何使用此Syntax jsObj['key' i] = 'example' 1;不工作。正确的方法采用方括号: jsobj ['key''i] ='example'1; 在JavaScript中,数组是一...
    编程 发布于2025-03-12
  • 如何使用不同数量列的联合数据库表?
    如何使用不同数量列的联合数据库表?
    合并列数不同的表 当尝试合并列数不同的数据库表时,可能会遇到挑战。一种直接的方法是在列数较少的表中,为缺失的列追加空值。 例如,考虑两个表,表 A 和表 B,其中表 A 的列数多于表 B。为了合并这些表,同时处理表 B 中缺失的列,请按照以下步骤操作: 确定表 B 中缺失的列,并将它们添加到表的末...
    编程 发布于2025-03-12
  • 如何从Python中的字符串中删除表情符号:固定常见错误的初学者指南?
    如何从Python中的字符串中删除表情符号:固定常见错误的初学者指南?
    从python import codecs import codecs import codecs 导入 text = codecs.decode('这狗\ u0001f602'.encode('utf-8'),'utf-8') 印刷(文字)#带有...
    编程 发布于2025-03-12
  • 如何使用组在MySQL中旋转数据?
    如何使用组在MySQL中旋转数据?
    在关系数据库中使用mySQL组使用mySQL组进行查询结果,在关系数据库中使用MySQL组,转移数据的数据是指重新排列的行和列的重排以增强数据可视化。在这里,我们面对一个共同的挑战:使用组的组将数据从基于行的基于列的转换为基于列。 Let's consider the following ...
    编程 发布于2025-03-12
  • 如何克服PHP的功能重新定义限制?
    如何克服PHP的功能重新定义限制?
    克服PHP的函数重新定义限制在PHP中,多次定义一个相同名称的函数是一个no-no。尝试这样做,如提供的代码段所示,将导致可怕的“不能重新列出”错误。 但是,PHP工具腰带中有一个隐藏的宝石:runkit扩展。它使您能够灵活地重新定义函数。 runkit_function_renction_re...
    编程 发布于2025-03-12
  • 为什么使用Firefox后退按钮时JavaScript执行停止?
    为什么使用Firefox后退按钮时JavaScript执行停止?
    导航历史记录问题:JavaScript使用Firefox Back Back 此行为是由浏览器缓存JavaScript资源引起的。要解决此问题并确保在后续页面访问中执行脚本,Firefox用户应设置一个空功能。 警报'); }; alert('inline Alert')...
    编程 发布于2025-03-12
  • 如何从PHP中的数组中提取随机元素?
    如何从PHP中的数组中提取随机元素?
    从阵列中的随机选择,可以轻松从数组中获取随机项目。考虑以下数组:; 从此数组中检索一个随机项目,利用array_rand( array_rand()函数从数组返回一个随机键。通过将$项目数组索引使用此键,我们可以从数组中访问一个随机元素。这种方法为选择随机项目提供了一种直接且可靠的方法。
    编程 发布于2025-03-12
  • 版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    在时间戳列上使用current_timestamp或MySQL版本中的current_timestamp或在5.6.5 此限制源于遗留实现的关注,这些限制需要对当前的_timestamp功能进行特定的实现。 创建表`foo`( `Productid` int(10)unsigned not n...
    编程 发布于2025-03-12

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3