react-native-cli指令流程分析

大體流程

我們執(zhí)行一個(gè)react-native init或start指令的時(shí)候入口在
react-native-cli/package.json

"bin": {
    "react-native": "index.js"
  },

從這里可以看到入口指向了react-native-cli/index.js,進(jìn)入index.js
分析代碼前先看一下文件注釋

react native cli已全局安裝在人們的計(jì)算機(jī)上。這意味著
很難讓他們升級(jí)版本因?yàn)橹话惭b了一個(gè)全局版本,所以很容易打破改變。react native cli的唯一工作是初始化存儲(chǔ)庫(kù),然后將所有命令轉(zhuǎn)發(fā)到react native的本地版本。如果需要添加新命令,請(qǐng)將其添加到本地cli/。修改此文件的唯一原因是添加了更多警告和“react native init”命令的疑難解答信息。不要做破壞性的改變!我們絕對(duì)不想告訴人們更新他們的react native cl的全局版本

所以說全局庫(kù)中只有init的指令方法,其他指令方法都在本地local-cli中,接下來分析一下代碼

//獲取指令參數(shù)
var options = require('minimist')(process.argv.slice(2));

//獲取react-native包下的cli路徑
var CLI_MODULE_PATH = function() {
  return path.resolve(
    process.cwd(),
    'node_modules',
    'react-native',
    'cli.js'
  );
};

//獲取react-native包下的package.json路徑
var REACT_NATIVE_PACKAGE_JSON_PATH = function() {
  return path.resolve(
    process.cwd(),
    'node_modules',
    'react-native',
    'package.json'
  );
};
...
//獲取cli文件
var cli;
var cliPath = CLI_MODULE_PATH();
if (fs.existsSync(cliPath)) {
  cli = require(cliPath);
}

//執(zhí)行指令
var commands = options._;
if (cli) {
  cli.run();
} else {
  if (options._.length === 0 && (options.h || options.help)) {
    console.log([
      '',
      '  Usage: react-native [command] [options]',
      '',
      '',
      '  Commands:',
      '',
      '    init <ProjectName> [options]  generates a new project and installs its dependencies',
      '',
      '  Options:',
      '',
      '    -h, --help    output usage information',
      '    -v, --version output the version number',
      '',
    ].join('\n'));
    process.exit(0);
  }

  if (commands.length === 0) {
    console.error(
      'You did not pass any commands, run `react-native --help` to see a list of all available commands.'
    );
    process.exit(1);
  }

  switch (commands[0]) {
  case 'init':
    if (!commands[1]) {
      console.error(
        'Usage: react-native init <ProjectName> [--verbose]'
      );
      process.exit(1);
    } else {
      init(commands[1], options);
    }
    break;
  default:
    console.error(
      'Command `%s` unrecognized. ' +
      'Make sure that you have run `npm install` and that you are inside a react-native project.',
      commands[0]
    );
    process.exit(1);
    break;
  }
}

前面是獲取指令參數(shù)和路徑信息,然后是require cli文件,開始執(zhí)行指令,判斷如果有cli則執(zhí)行cli.run,否則執(zhí)行當(dāng)前文件的邏輯。

init指令邏輯

生成項(xiàng)目會(huì)走到init方法,最后執(zhí)行到run方法

/**
 * @param name Project name, e.g. 'AwesomeApp'.
 * @param options.verbose If true, will run 'npm install' in verbose mode (for debugging).
 * @param options.version Version of React Native to install, e.g. '0.38.0'.
 * @param options.npm If true, always use the npm command line client,
 *                       don't use yarn even if available.
 */
function init(name, options) {
  validateProjectName(name);

  if (fs.existsSync(name)) {
    createAfterConfirmation(name, options);
  } else {
    createProject(name, options);
  }
}
function run(root, projectName, options) {
  // E.g. '0.38' or '/path/to/archive.tgz'
  const rnPackage = options.version;
  const forceNpmClient = options.npm;
  const yarnVersion = (!forceNpmClient) && getYarnVersionIfAvailable();
  var installCommand;
  if (options.installCommand) {
    // In CI environments it can be useful to provide a custom command,
    // to set up and use an offline mirror for installing dependencies, for example.
    installCommand = options.installCommand;
  } else {
    if (yarnVersion) {
      console.log('Using yarn v' + yarnVersion);
      console.log('Installing ' + getInstallPackage(rnPackage) + '...');
      installCommand = 'yarn add ' + getInstallPackage(rnPackage) + ' --exact';
      if (options.verbose) {
        installCommand += ' --verbose';
      }
    } else {
      console.log('Installing ' + getInstallPackage(rnPackage) + '...');
      if (!forceNpmClient) {
        console.log('Consider installing yarn to make this faster: https://yarnpkg.com');
      }
      installCommand = 'npm install --save --save-exact ' + getInstallPackage(rnPackage);
      if (options.verbose) {
        installCommand += ' --verbose';
      }
    }
  }
  try {
    execSync(installCommand, {stdio: 'inherit'});
  } catch (err) {
    console.error(err);
    console.error('Command `' + installCommand + '` failed.');
    process.exit(1);
  }
  checkNodeVersion();
  cli = require(CLI_MODULE_PATH());
  cli.init(root, projectName);
}

后面分別會(huì)創(chuàng)建項(xiàng)目、安裝yarn依賴、安裝react-native依賴,然后獲取到react-native的cli路徑,執(zhí)行cli的init方法。

/**
 * Creates the template for a React Native project given the provided
 * parameters:
 * @param projectDir Templates will be copied here.
 * @param argsOrName Project name or full list of custom arguments
 *                   for the generator.
 * @param options Command line options passed from the react-native-cli directly.
 *                E.g. `{ version: '0.43.0', template: 'navigation' }`
 */
function init(projectDir, argsOrName) {
  const args = Array.isArray(argsOrName)
    ? argsOrName // argsOrName was e.g. ['AwesomeApp', '--verbose']
    : [argsOrName].concat(process.argv.slice(4)); // argsOrName was e.g. 'AwesomeApp'

  // args array is e.g. ['AwesomeApp', '--verbose', '--template', 'navigation']
  if (!args || args.length === 0) {
    console.error('react-native init requires a project name.');
    return;
  }

  const newProjectName = args[0];
  const options = minimist(args);

  if (listTemplatesAndExit(newProjectName, options)) {
    // Just listing templates using 'react-native init --template'
    // Not creating a new app.
    return;
  } else {
    console.log('Setting up new React Native app in ' + projectDir);
    generateProject(projectDir, newProjectName, options);
  }
}

至此init指令流程基本分析完畢,有興趣的童鞋可以跟一下代碼

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容