Interpretation of /packages/react-scripts of the core source code of create-react-app scaffolding

React Official Scaffolding

  • Take version 5.0.1 as an example
  • Create a project execution process

Source code interpretation debug

Create a project create-react-app my-app, interpret the previous /packages/create-react-appsource code, you can interpret it from the pacakage/create-react-app core source code of create-react-app in detail (1)

Equivalent to packages/react-scriptsrunning the command:

yarn init

Below scripts/init.js, the code executes parsing on demand from top to bottom

1. Enter the function

 const appPackage = require(path.join(appPath, 'package.json'));
  • debugcode show as below:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-uRdNi6cc-1658403349318)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /e7e16091a7954e5099162f9b55e7f229~tplv-k3u1fbpfcp-watermark.image?)]

  • Then execute and useyarnreturn , because the dependencies of the installation falseused earliernpm
  • templateNameThe value is cra-template;
  • templatePathThe running value is 'my-app/node_modules/cra-template';
  • templateJsonPathoperating value'my-app/node_modules/cra-template/template.json'
  • Get templateJsonthe read value as:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-GLsDDf3F-1658403349320)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /91c9690e6e9c4e848d8efe29c3678710~tplv-k3u1fbpfcp-watermark.image?)]

2. templatePackageToReplace

execute returnfalse

3. Add in the new my-appproject , the specific source code is as follows:package.jsonscripts

appPackage.scripts = Object.assign(
    {
    
    
      start: 'react-scripts start',
      build: 'react-scripts build',
      test: 'react-scripts test',
      eject: 'react-scripts eject',
    },
    templateScripts
  );

Is it familiar here? create-react-appThe project initialized by scaffolding package.jsonis like this

4. Set eslint config

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

5. Set the browsers list

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-a9bkHHnE-1658403349320)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /f37d096d8e974071819bdc8162b581cf~tplv-k3u1fbpfcp-watermark.image?)]

6. Asynchronous writepackage.json

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

After the execution is complete, go to the newly created project my-appto view the following:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-YfCIbDzM-1658403349321)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /7eeead3d8aa74863b33cc6303c6c33b8~tplv-k3u1fbpfcp-watermark.image?)]

  • Determine whether it exists README.md, returnfalse

8. Copy the template project to the new project directory

In create-react-app/packagesthe directory, you can see the project template cra-templatefor initialization

  • templateDirThe operating value is'my-app/node_modules/cra-template/template'
  • appPathThe operating value is'/Users/coco/project/shiqiang/create-react-app/packages/my-app'
  • Source Code Execution Copy
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;
  }

After running, go my-appto view, the directory at this time is as follows:

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-IZf2FE1w-1658403349321)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /3149ca457315447681c4173274d7fdab~tplv-k3u1fbpfcp-watermark.image?)]

.gitignorefile does not exist

9. Determine whether it exists.gitignore

The source code is as follows:

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'),
      []
    );
  }

Return false, then enter else, the operation is completed, and the new project gitignoreis replaced with.gitignore

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-FakKYryk-1658403349322)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /0ffee6076190403e8c81c833133c43e6~tplv-k3u1fbpfcp-watermark.image?)]

10. Initializationgit repo

The source code is as follows:

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;
  }
}
  • 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);
  }
  • Install additional template dependencies (if present)
const dependenciesToInstall = Object.entries({
    
    
    ...templatePackage.dependencies,
    ...templatePackage.devDependencies,
  });
  if (dependenciesToInstall.length) {
    
    
    args = args.concat(
      dependenciesToInstall.map(([dependency, version]) => {
    
    
        return `${
      
      dependency}@${
      
      version}`;
      })
    );
  }

debugdata:

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-sinIYTHz-1658403349322)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /1bc4cccd2eed4fcab39676aa0fc361fb~tplv-k3u1fbpfcp-watermark.image?)]

argsOperating data:

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-PVgLaZfV-1658403349323)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /6c06bc59d12a4eb2987cac9e29fca75d~tplv-k3u1fbpfcp-watermark.image?)]

11. Determine whether to install react

  • The source code is as follows:
 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;
    }
  }
  • functionisReactInstalled
function isReactInstalled(appPackage) {
    
    
  const dependencies = appPackage.dependencies || {
    
    };

  return (
    typeof dependencies.react !== 'undefined' &&
    typeof dependencies['react-dom'] !== 'undefined'
  );
}
  • Key print information:
    [External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-KTibyfm4-1658403349323)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /138b047ee60d4ebe96d7ad3c222ce4ae~tplv-k3u1fbpfcp-watermark.image?)]

12. The child process executes the installation command

  • The source code is as follows:
 const proc = spawn.sync(command, args, {
    
     stdio: 'inherit' });
  • The console operation information is as follows:

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-WdJ6v5U4-1658403349324)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /f9774a075a734e0b80553f1f30697bbc~tplv-k3u1fbpfcp-watermark.image?)]

13. Execute delete, delete node_modulesthe directorycra-template

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-JsjGCYba-1658403349324)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/73ccab30be82492e8dba4f2f1bf04244~tplv-k3u1fbpfcp-watermark.image?)]

14. Show the most elegant way to cd

  • The source code is as follows:
 let cdpath;
  if (originalDirectory && path.join(originalDirectory, appName) === appPath) {
    
    
    cdpath = appName;
  } else {
    
    
    cdpath = appPath;
  }

After running cdpaththe value ismy-app

15. Success message prompt printing

  • The source code is as follows:
 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!');
  • The console print information is as follows:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-h6EXEnvb-1658403349324)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /3f0239cddb11432b982d626e4d23bd08~tplv-k3u1fbpfcp-watermark.image?)]

At this point, react-scriptsthe completion of the new project

Guess you like

Origin blog.csdn.net/gkf6104/article/details/125919523