大體流程
我們執(zhí)行一個react-native init或start指令的時候入口在
react-native-cli/package.json
"bin": {
"react-native": "index.js"
},
從這里可以看到入口指向了react-native-cli/index.js,進入index.js
分析代碼前先看一下文件注釋
react native cli已全局安裝在人們的計算機上薇缅。這意味著
很難讓他們升級版本因為只安裝了一個全局版本剩失,所以很容易打破改變鹃锈。react native cli的唯一工作是初始化存儲庫裳擎,然后將所有命令轉發(fā)到react native的本地版本吁脱。如果需要添加新命令尤溜,請將其添加到本地cli/谒亦。修改此文件的唯一原因是添加了更多警告和“react native init”命令的疑難解答信息竭宰。不要做破壞性的改變!我們絕對不想告訴人們更新他們的react native cl的全局版本
所以說全局庫中只有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í)行當前文件的邏輯谐腰。
init指令邏輯
生成項目會走到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);
}
后面分別會創(chuà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指令流程基本分析完畢叶眉,有興趣的童鞋可以跟一下代碼