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-app
source 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-scripts
running 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'));
debug
code show as below:
- Then execute and
useyarn
return , because the dependencies of the installationfalse
used earliernpm
templateName
The value iscra-template
;templatePath
The running value is'my-app/node_modules/cra-template'
;templateJsonPath
operating value'my-app/node_modules/cra-template/template.json'
- Get
templateJson
the read value as:
2. templatePackageToReplace
execute returnfalse
3. Add in the new my-app
project , the specific source code is as follows:package.json
scripts
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-app
The project initialized by scaffolding package.json
is like this
4. Set eslint config
appPackage.eslintConfig = {
extends: 'react-app',
};
5. Set the browsers list
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-app
to view the following:
- Determine whether it exists
README.md
, returnfalse
8. Copy the template project to the new project directory
In create-react-app/packages
the directory, you can see the project template cra-template
for initialization
templateDir
The operating value is'my-app/node_modules/cra-template/template'
appPath
The 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-app
to view, the directory at this time is as follows:
.gitignore
file 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 gitignore
is replaced with.gitignore
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}`;
})
);
}
debug
data:
args
Operating data:
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;
}
}
- function
isReactInstalled
function isReactInstalled(appPackage) {
const dependencies = appPackage.dependencies || {
};
return (
typeof dependencies.react !== 'undefined' &&
typeof dependencies['react-dom'] !== 'undefined'
);
}
- Key print information:
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:
13. Execute delete, delete node_modules
the 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-
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 cdpath
the 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:
At this point, react-scripts
the completion of the new project