網站首頁 編程語言 正文
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
代碼如下:
- 接著執行,
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-app
的package.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
6. 異步寫入package.json
fs.writeFileSync(
path.join(appPath, 'package.json'),
JSON.stringify(appPackage, null, 2) + os.EOL
);
執行完成后,就去新建的項目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;
}
運行完,去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'),
[]
);
}
返回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;
}
}
-
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
數據:
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;
}
}
- 函數
isReactInstalled
function isReactInstalled(appPackage) {
const dependencies = appPackage.dependencies || {};
return (
typeof dependencies.react !== 'undefined' &&
typeof dependencies['react-dom'] !== 'undefined'
);
}
- 關鍵打印信息:
12. 子進程執行安裝命令
- 源碼如下:
const proc = spawn.sync(command, args, { stdio: 'inherit' });
- 控制臺運行信息如下:
13. 執行刪除,刪除node_modules
目錄下的cra-template
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-JsjGCYba-
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!');
- 控制臺打印信息如下:
至此,新建項目react-scripts
中的完成
原文鏈接:https://blog.csdn.net/gkf6104/article/details/125919523
- 上一篇:如何快速刪除node_modules目錄方法詳解
- 下一篇:UC瀏覽器兼容問題
相關推薦
- 2022-07-02 如何對numpy?矩陣進行通道間求均值_python
- 2022-12-30 一文帶你了解Go語言中接口的使用_Golang
- 2022-10-26 Python?Pyinstaller庫安裝步驟以及使用方法_python
- 2022-05-17 MacOS系統(macmini macbook pro)上安裝RabbitMQ
- 2023-10-16 Element UI日期組件-選擇月份具體到當月最后一天
- 2022-06-29 tomcat下部署jenkins的實現方法_Tomcat
- 2022-07-23 C++深入淺出探索數據結構的原理_C 語言
- 2022-09-29 Python組合數據類型詳解_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支