本文做者:IMWeb IMWeb团队 原文出处:IMWeb社区 未经赞成,禁止转载css
create-react-app是一个react的cli脚手架+构建器,咱们能够基于CRA零配置直接上手开发一个react的SPA应用。 经过3种方式快速建立一个React SPA应用:html
npm init
with initializer (npm 6.1+)npx
with generator (npm 5.2+)yarn create
with initializer (yarn 0.25+)例如咱们新建一个叫my-app的SPA:node
my-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js
复制代码
经过添加参数生成ts支持:react
npx create-react-app my-app --typescript
# or
yarn create react-app my-app --typescript
复制代码
固然,若是咱们是把一个CRA已经生成的js项目改为支持ts,能够:webpack
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
# or
yarn add typescript @types/node @types/react @types/react-dom @types/jest
复制代码
而后,将.js文件后缀改为.ts重启development server便可。git
CRA除了能帮咱们构建出一个React的SPA项目(generator),充当脚手架的做用。还能为咱们在项目开发,编译时进行构建,充当builder的做用。能够看到生成的项目中的package.json
包含不少命令:github
react-scripts start
启动开发模式下的一个dev-server,并支持代码修改时的Hot Reload
react-scripts build
使用webpack进行编译打包,生成生产模式下的全部脚本,静态资源react-scripts test
执行全部测试用例,完成对咱们每一个模块质量的保证这里,咱们针对start这条线进行追踪,探查CRA实现的原理。入口为create-react-app/packages/react-scripts/bin/react-scripts.js
,这个脚本会在react-scripts中设置到package.json
的bin字段中去,也就是说这个package能够做为可执行的nodejs脚本,经过cli方式在nodejs宿主环境中。这个入口脚本很是简单,这里只列出主要的一个switch
分支:web
switch (script) {
case 'build':
case 'eject':
case 'start':
case 'test': {
const result = spawn.sync(
'node',
nodeArgs
.concat(require.resolve('../scripts/' + script))
.concat(args.slice(scriptIndex + 1)),
{ stdio: 'inherit' }
);
if (result.signal) {
if (result.signal === 'SIGKILL') {
console.log(
'The build failed because the process exited too early. ' +
'This probably means the system ran out of memory or someone called ' +
'`kill -9` on the process.'
);
} else if (result.signal === 'SIGTERM') {
console.log(
'The build failed because the process exited too early. ' +
'Someone might have called `kill` or `killall`, or the system could ' +
'be shutting down.'
);
}
process.exit(1);
}
process.exit(result.status);
break;
}
default:
console.log('Unknown script "' + script + '".');
console.log('Perhaps you need to update react-scripts?');
console.log(
'See: https://facebook.github.io/create-react-app/docs/updating-to-new-releases'
);
break;
}
复制代码
能够看到,当根据不一样command,会分别resolve不一样的js脚本,执行不一样的任务,这里咱们继续看require('../scripts/start')
:chrome
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
复制代码
由于是开发模式,因此这里把babel,node的环境变量都设置为development
,而后是全局错误的捕获,这些都是一个cli脚本一般的处理方式:typescript
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
复制代码
确保其余的环境变量配置也读进进程了,因此这里会经过../config/env
脚本进行初始化:
// Ensure environment variables are read.
require('../config/env');
复制代码
还有一些预检查,这部分是做为eject以前对项目目录的检查,这里由于eject不在咱们范围,直接跳过。而后进入到了咱们主脚本的依赖列表:
const fs = require('fs');
const chalk = require('react-dev-utils/chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const configFactory = require('../config/webpack.config');
const createDevServerConfig = require('../config/webpackDevServer.config');
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
复制代码
能够看到,主要的依赖仍是webpack,WDS,以及自定义的一些devServer的configuration以及webpack的configuration,能够大胆猜测原理和咱们平时使用webpack并无什么不一样。
由于create-react-app my-app
以后经过模版生成的项目中入口脚本被放置在src/index.js,而入口html被放置在public/index.html,因此须要对这两个文件进行检查:
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
复制代码
下面这部分是涉及C9云部署时的环境变量检查,不在咱们考究范围,也直接跳过。react-dev-utils/browsersHelper
是一个浏览器支持的帮助utils,由于在react-scripts v2
以后必需要提供一个browser list支持列表,不过咱们能够在package.json
中看到,模版项目中已经为咱们生成了:
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
复制代码
检查完devServer端口后,进入咱们核心逻辑执行,这里的主线仍是和咱们使用webpack方式几乎没什么区别,首先会经过configFactory
建立出一个webpack的configuration object,而后经过createDevServerConfig
建立出一个devServer的configuration object,而后传递webpack config实例化一个webpack compiler实例,传递devServer的configuration实例化一个WDS实例开始监听指定的端口,最后经过openBrowser调用咱们的浏览器,打开咱们的SPA。
其实,整个流程咱们看到这里,已经结束了,咱们知道WDS和webpack配合,能够进行热更,file changes watching等功能,咱们开发时,经过修改源代码,或者样式文件,会被实时监听,而后webpack中的HWR会实时刷新浏览器页面,能够很方便的进行实时调试开发。
const config = configFactory('development');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const useTypeScript = fs.existsSync(paths.appTsConfig);
const urls = prepareUrls(protocol, HOST, port);
const devSocket = {
warnings: warnings =>
devServer.sockWrite(devServer.sockets, 'warnings', warnings),
errors: errors =>
devServer.sockWrite(devServer.sockets, 'errors', errors),
};
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler({
appName,
config,
devSocket,
urls,
useYarn,
useTypeScript,
webpack,
});
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web server.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
// We used to support resolving modules according to `NODE_PATH`.
// This now has been deprecated in favor of jsconfig/tsconfig.json
// This lets you use absolute paths in imports inside large monorepos:
if (process.env.NODE_PATH) {
console.log(
chalk.yellow(
'Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.'
)
);
console.log();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
复制代码
经过start
命令的追踪,咱们知道CRA最终仍是经过WDS和webpack进行开发监听的,其实build
会比start
更简单,只是在webpack configuration中会进行优化。CRA作到了能够0配置,就能进行react项目的开发,调试,打包。
实际上是由于CRA把复杂的webpack config配置封装起来了,把babel plugins预设好了,把开发时会经常使用到的一个环境检查,polyfill兼容都给开发者作了,因此使用起来会比咱们直接使用webpack,本身进行重复的配置信息设置要来的简单不少。