掘金迁移过来,图片有问题,有兴趣可以查看我的掘金文章 原文:https://juejin.cn/post/7122436068812521479

# React官方脚手架

  • 以5.0.1版本为例
  • 创建项目执行过程

# 源码解读debug

创建项目create-react-app my-app,前面/packages/create-react-app源码解读,详细可以从create-react-app之pacakage/create-react-app核心源码解读(一) (opens new window)

相当于在packages/react-scripts运行命令:

yarn init
1

以下scripts/init.js,代码从上到下按需执行解析

# 1. 进入函数

 const appPackage = require(path.join(appPath, 'package.json'));
1
  • debug代码如下:
  • 接着执行,useyarn返回false,因为前面使用的npm安装的依赖
  • templateName的值为cra-template
  • templatePath运行值为'my-app/node_modules/cra-template';
  • templateJsonPath运行值'my-app/node_modules/cra-template/template.json'
  • 获取templateJson读取值为:

# 2. templatePackageToReplace

执行返回false

# 3. 新建项目my-apppackage.json中添加scripts,具体源码如下:

appPackage.scripts = Object.assign(
    {
      start: 'react-scripts start',
      build: 'react-scripts build',
      test: 'react-scripts test',
      eject: 'react-scripts eject',
    },
    templateScripts
  );
1
2
3
4
5
6
7
8
9

到这里是不是很眼熟,create-react-app脚手架初始化的项目,package.json中就是这样

# 4. 设置 eslint config

 appPackage.eslintConfig = {
   extends: 'react-app',
 };
1
2
3

# 5. 设置browers list

# 6. 异步写入package.json

fs.writeFileSync(
    path.join(appPath, 'package.json'),
    JSON.stringify(appPackage, null, 2) + os.EOL
  );
1
2
3
4

执行完成后,就去新建的项目my-app下查看如下:

  • 判断是否存在README.md,返回false

# 8. 拷贝模版项目到新建项目目录下

create-react-app/packages目录下可以看到有cra-template为初始化项目模版

  • templateDir运行值为'my-app/node_modules/cra-template/template'
  • appPath运行值为'/Users/coco/project/shiqiang/create-react-app/packages/my-app'
  • 源码执行拷贝
const templateDir = path.join(templatePath, 'template');
  if (fs.existsSync(templateDir)) {
    fs.copySync(templateDir, appPath);
  } else {
    console.error(
      `Could not locate supplied template: ${chalk.green(templateDir)}`
    );
    return;
  }
1
2
3
4
5
6
7
8
9

运行完,去my-app下查看,此时的目录如下:

不存在.gitignore文件

# 9. 判断是否存在.gitignore

源码如下:

const gitignoreExists = fs.existsSync(path.join(appPath, '.gitignore'));
  if (gitignoreExists) {
    // Append if there's already a `.gitignore` file there
    const data = fs.readFileSync(path.join(appPath, 'gitignore'));
    fs.appendFileSync(path.join(appPath, '.gitignore'), data);
    fs.unlinkSync(path.join(appPath, 'gitignore'));
  } else {
    // Rename gitignore after the fact to prevent npm from renaming it to .npmignore
    // See: https://github.com/npm/npm/issues/1862
    fs.moveSync(
      path.join(appPath, 'gitignore'),
      path.join(appPath, '.gitignore'),
      []
    );
  }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

返回false,于是进入else,运行完成,新建项目gitignore替换为.gitignore

# 10. 初始化git repo

源码如下:

function tryGitInit() {
  try {
    execSync('git --version', { stdio: 'ignore' });
    if (isInGitRepository() || isInMercurialRepository()) {
      return false;
    }

    execSync('git init', { stdio: 'ignore' });
    return true;
  } catch (e) {
    console.warn('Git repo not initialized', e);
    return false;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  • yarn ornpm
  if (useYarn) {
    command = 'yarnpkg';
    remove = 'remove';
    args = ['add'];
  } else {
    command = 'npm';
    remove = 'uninstall';
    args = [
      'install',
      '--no-audit', // https://github.com/facebook/create-react-app/issues/11174
      '--save',
      verbose && '--verbose',
    ].filter(e => e);
  }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  • 安装其他模板依赖项(如果存在)
const dependenciesToInstall = Object.entries({
    ...templatePackage.dependencies,
    ...templatePackage.devDependencies,
  });
  if (dependenciesToInstall.length) {
    args = args.concat(
      dependenciesToInstall.map(([dependency, version]) => {
        return `${dependency}@${version}`;
      })
    );
  }
1
2
3
4
5
6
7
8
9
10
11

debug数据:

args运行数据:

# 11. 判断是否安装react

  • 源码如下:
 if ((!isReactInstalled(appPackage) || templateName) && args.length > 1) {
    console.log();
    console.log(`Installing template dependencies using ${command}...`);

    const proc = spawn.sync(command, args, { stdio: 'inherit' });
    if (proc.status !== 0) {
      console.error(`\`${command} ${args.join(' ')}\` failed`);
      return;
    }
  }
1
2
3
4
5
6
7
8
9
10
  • 函数isReactInstalled
function isReactInstalled(appPackage) {
  const dependencies = appPackage.dependencies || {};

  return (
    typeof dependencies.react !== 'undefined' &&
    typeof dependencies['react-dom'] !== 'undefined'
  );
}
1
2
3
4
5
6
7
8
  • 关键打印信息:

# 12. 子进程执行安装命令

  • 源码如下:
 const proc = spawn.sync(command, args, { stdio: 'inherit' });
1
  • 控制台运行信息如下:

# 13. 执行删除,删除node_modules目录下的cra-template

# 14. 显示最优雅的 cd 方式

  • 源码如下:
 let cdpath;
  if (originalDirectory && path.join(originalDirectory, appName) === appPath) {
    cdpath = appName;
  } else {
    cdpath = appPath;
  }
1
2
3
4
5
6

运行后cdpath值为my-app

# 15. 成功信息提示打印

  • 源码如下:
 const displayedCommand = useYarn ? 'yarn' : 'npm';

  console.log();
  console.log(`Success! Created ${appName} at ${appPath}`);
  console.log('Inside that directory, you can run several commands:');
  console.log();
  console.log(chalk.cyan(`  ${displayedCommand} start`));
  console.log('    Starts the development server.');
  console.log();
  console.log(
    chalk.cyan(`  ${displayedCommand} ${useYarn ? '' : 'run '}build`)
  );
  console.log('    Bundles the app into static files for production.');
  console.log();
  console.log(chalk.cyan(`  ${displayedCommand} test`));
  console.log('    Starts the test runner.');
  console.log();
  console.log(
    chalk.cyan(`  ${displayedCommand} ${useYarn ? '' : 'run '}eject`)
  );
  console.log(
    '    Removes this tool and copies build dependencies, configuration files'
  );
  console.log(
    '    and scripts into the app directory. If you do this, you can’t go back!'
  );
  console.log();
  console.log('We suggest that you begin by typing:');
  console.log();
  console.log(chalk.cyan('  cd'), cdpath);
  console.log(`  ${chalk.cyan(`${displayedCommand} start`)}`);
  if (readmeExists) {
    console.log();
    console.log(
      chalk.yellow(
        'You had a `README.md` file, we renamed it to `README.old.md`'
      )
    );
  }
  console.log();
  console.log('Happy hacking!');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  • 控制台打印信息如下:

至此,新建项目react-scripts中的完成