日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

create-react-app腳手架核心源碼之/packages/react-scripts解讀

作者:coco723? 更新時間: 2022-07-22 編程語言

React官方腳手架

  • 以5.0.1版本為例
  • 創建項目執行過程

源碼解讀debug

創建項目create-react-app my-app,前面/packages/create-react-app源碼解讀,詳細可以從create-react-app之pacakage/create-react-app核心源碼解讀(一)

相當于在packages/react-scripts運行命令:

yarn init

以下scripts/init.js,代碼從上到下按需執行解析

1. 進入函數

 const appPackage = require(path.join(appPath, 'package.json'));
  • debug代碼如下:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-uRdNi6cc-1658403349318)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/e7e16091a7954e5099162f9b55e7f229~tplv-k3u1fbpfcp-watermark.image?)]

  • 接著執行,useyarn返回false,因為前面使用的npm安裝的依賴
  • templateName的值為cra-template
  • templatePath運行值為'my-app/node_modules/cra-template';
  • templateJsonPath運行值'my-app/node_modules/cra-template/template.json'
  • 獲取templateJson讀取值為:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-GLsDDf3F-1658403349320)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/91c9690e6e9c4e848d8efe29c3678710~tplv-k3u1fbpfcp-watermark.image?)]

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
  );

到這里是不是很眼熟,create-react-app腳手架初始化的項目,package.json中就是這樣

4. 設置 eslint config

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

5. 設置browers list

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-a9bkHHnE-1658403349320)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f37d096d8e974071819bdc8162b581cf~tplv-k3u1fbpfcp-watermark.image?)]

6. 異步寫入package.json

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

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

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-YfCIbDzM-1658403349321)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7eeead3d8aa74863b33cc6303c6c33b8~tplv-k3u1fbpfcp-watermark.image?)]

  • 判斷是否存在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;
  }

運行完,去my-app下查看,此時的目錄如下:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-IZf2FE1w-1658403349321)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/3149ca457315447681c4173274d7fdab~tplv-k3u1fbpfcp-watermark.image?)]

不存在.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'),
      []
    );
  }

返回false,于是進入else,運行完成,新建項目gitignore替換為.gitignore

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-FakKYryk-1658403349322)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0ffee6076190403e8c81c833133c43e6~tplv-k3u1fbpfcp-watermark.image?)]

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;
  }
}
  • 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);
  }
  • 安裝其他模板依賴項(如果存在)
const dependenciesToInstall = Object.entries({
    ...templatePackage.dependencies,
    ...templatePackage.devDependencies,
  });
  if (dependenciesToInstall.length) {
    args = args.concat(
      dependenciesToInstall.map(([dependency, version]) => {
        return `${dependency}@${version}`;
      })
    );
  }

debug數據:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-sinIYTHz-1658403349322)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/1bc4cccd2eed4fcab39676aa0fc361fb~tplv-k3u1fbpfcp-watermark.image?)]

args運行數據:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-PVgLaZfV-1658403349323)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6c06bc59d12a4eb2987cac9e29fca75d~tplv-k3u1fbpfcp-watermark.image?)]

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;
    }
  }
  • 函數isReactInstalled
function isReactInstalled(appPackage) {
  const dependencies = appPackage.dependencies || {};

  return (
    typeof dependencies.react !== 'undefined' &&
    typeof dependencies['react-dom'] !== 'undefined'
  );
}
  • 關鍵打印信息:
    [外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-KTibyfm4-1658403349323)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/138b047ee60d4ebe96d7ad3c222ce4ae~tplv-k3u1fbpfcp-watermark.image?)]

12. 子進程執行安裝命令

  • 源碼如下:
 const proc = spawn.sync(command, args, { stdio: 'inherit' });
  • 控制臺運行信息如下:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-WdJ6v5U4-1658403349324)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f9774a075a734e0b80553f1f30697bbc~tplv-k3u1fbpfcp-watermark.image?)]

13. 執行刪除,刪除node_modules目錄下的cra-template

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-JsjGCYba-1658403349324)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/73ccab30be82492e8dba4f2f1bf04244~tplv-k3u1fbpfcp-watermark.image?)]

14. 顯示最優雅的 cd 方式

  • 源碼如下:
 let cdpath;
  if (originalDirectory && path.join(originalDirectory, appName) === appPath) {
    cdpath = appName;
  } else {
    cdpath = appPath;
  }

運行后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!');
  • 控制臺打印信息如下:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-h6EXEnvb-1658403349324)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/3f0239cddb11432b982d626e4d23bd08~tplv-k3u1fbpfcp-watermark.image?)]

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

原文鏈接:https://blog.csdn.net/gkf6104/article/details/125919523

欄目分類
最近更新