繁体   English   中英

如何以编程方式启动/停止Metro Bundler

[英]How to programmatically start/stop Metro Bundler

我正在尝试为React-Native项目设置持续集成,并在端到端测试中遇到一些问题,尤其是在Metro捆绑器周围。

在这种情况下,使用react-native脚本似乎不可靠:

  • iOS构建自发地在新终端中生成捆绑程序,并使其在构建后运行。
  • Android构建依赖于正在运行的实例,该实例必须事先手动启动。
  • 捆绑程序只能通过发信号(Ctrl + C或kill)来停止。
  • 与构建没有同步,以确保在应用启动时捆绑程序已准备好进行处理。

我想编写一个自定义脚本,该脚本可以启动Metro,在服务器准备就绪后运行测试,最后停止服务器以清理环境。

Metro捆绑器必须作为单独的进程运行,以便能够处理请求。 这样做的方法是使用子进程:生成并保留返回的对象以进行正确清理。

这是一个基本脚本,可同时启动Metro和Gradle,并根据它们的日志输出等待直到两者准备就绪。

'use strict';

const cp = require('child_process');
const fs = require('fs');
const readline = require('readline');

// List of sub processes kept for proper cleanup
const children = {};

async function asyncPoint(ms, callback = () => {}) {
  return await new Promise(resolve => setTimeout(() => {
    resolve(callback());
  }, ms));
}

async function fork(name, cmd, args, {readyRegex, timeout} = {}) {

  return new Promise((resolve) => {

    const close = () => {
      delete children[name];
      resolve(false);
    };

    if(timeout) {
      setTimeout(() => close, timeout);
    }

    const child = cp.spawn(
      cmd,
      args,
      {
        silent: false,
        stdio: [null, 'pipe', 'pipe'],
      },
    );

    child.on('close', close);
    child.on('exit', close);
    child.on('error', close);

    const output = fs.createWriteStream(`./volatile-build-${name}.log`);

    const lineCb = (line) => {
      console.log(`[${name}] ${line}`);
      output.write(line+'\n');
      if (readyRegex && line.match(readyRegex)) {
        resolve(true);
      }
    };

    readline.createInterface({
      input: child.stdout,
    }).on('line', lineCb);

    readline.createInterface({
      input: child.stderr,
    }).on('line', lineCb);

    children[name] = child;
  });
}

async function sighandle() {
  console.log('\nClosing...');
  Object.values(children).forEach(child => child.kill('SIGTERM'));
  await asyncPoint(1000);
  process.exit(0);
}

function setSigHandler() {
  process.on('SIGINT', sighandle);
  process.on('SIGTERM', sighandle);
}

async function main() {

  setSigHandler();

  // Metro Bundler
  const metroSync = fork(
    'metro',
    process.argv0,
    [ // args
      './node_modules/react-native/local-cli/cli.js', 
      'start',
    ],
    { // options
      readyRegex: /Loading dependency graph, done./,
      timeout: 60000,
    }
  );

  // Build APK
  const buildSync = fork(
    'gradle',
    './android/gradlew', 
    [ // args
      `--project-dir=${__dirname}/android`,
      'assembleDebug',
    ],
    { // options
      readyRegex: /BUILD SUCCESSFUL/,
      timeout: 300000,
    }
  );

  if (await metroSync && await buildSync) {

    // TODO: Run tests here

  }

  sighandle();
}

main();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM