create-react-app初探

本文由 IMWeb 社区 imweb.io 受权转载自腾讯内部 KM 论坛,原做者:kingfo。点击阅读原文查看 IMWeb 社区更多精彩文章。css

create-react-app是一个react的cli脚手架+构建器,咱们能够基于CRA零配置直接上手开发一个react的SPA应用经过3种方式快速建立一个React SPA应用:

  1. npm init with initializer (npm 6.1+)html

  2. npx with generator (npm 5.2+)node

  3. yarn create with initializer (yarn 0.25+)react

例如咱们新建一个叫my-app的SPA:webpack

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支持:git

npx create-react-app my-app --typescript# oryarn create react-app my-app --typescript

固然,若是咱们是把一个CRA已经生成的js项目改为支持ts,能够:github

npm install --save typescript @types/node @types/react @types/react-dom @types/jest# oryarn add typescript @types/node @types/react @types/react-dom @types/jest

而后,将.js文件后缀改为.ts重启development server便可。web

CRA还能干吗

CRA除了能帮咱们构建出一个React的SPA项目(generator),充当脚手架的做用。还能为咱们在项目开发,编译时进行构建,充当builder的做用。能够看到生成的项目中的 package.json包含不少命令:chrome

  1. react-scripts start启动开发模式下的一个dev-server,并支持代码修改时的 HotReloadtypescript

  2. react-scripts build使用webpack进行编译打包,生成生产模式下的全部脚本,静态资源

  3. 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分支:

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

// 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脚本一般的处理方式:

// 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不在咱们范围,直接跳过。而后进入到了咱们主脚本的依赖列表:

 
 
  1. const fs = require('fs');

  2. const chalk = require('react-dev-utils/chalk');

  3. const webpack = require('webpack');

  4. const WebpackDevServer = require('webpack-dev-server');

  5. const clearConsole = require('react-dev-utils/clearConsole');

  6. const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');

  7. const {

  8.  choosePort,

  9.  createCompiler,

  10.  prepareProxy,

  11.  prepareUrls,

  12. } = require('react-dev-utils/WebpackDevServerUtils');

  13. const openBrowser = require('react-dev-utils/openBrowser');

  14. const paths = require('../config/paths');

  15. const configFactory = require('../config/webpack.config');

  16. const createDevServerConfig = require('../config/webpackDevServer.config');


  17. const useYarn = fs.existsSync(paths.yarnLockFile);

  18. const isInteractive = process.stdout.isTTY;

能够看到,主要的依赖仍是webpack,WDS,以及自定义的一些devServer的configuration以及webpack的configuration,能够大胆猜测原理和咱们平时使用webpack并无什么不一样。

由于 create-react-appmy-app以后经过模版生成的项目中入口脚本被放置在src/index.js,而入口html被放置在public/index.html,因此须要对这两个文件进行检查:

// Warn and crash if required files are missingif (!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会实时刷新浏览器页面,能够很方便的进行实时调试开发。

 
 
  1. const config = configFactory('development');

  2. const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';

  3. const appName = require(paths.appPackageJson).name;

  4. const useTypeScript = fs.existsSync(paths.appTsConfig);

  5. const urls = prepareUrls(protocol, HOST, port);

  6. const devSocket = {

  7.  warnings: warnings =>

  8.    devServer.sockWrite(devServer.sockets, 'warnings', warnings),

  9.  errors: errors =>

  10.    devServer.sockWrite(devServer.sockets, 'errors', errors),

  11. };

  12. // Create a webpack compiler that is configured with custom messages.

  13. const compiler = createCompiler({

  14.  appName,

  15.  config,

  16.  devSocket,

  17.  urls,

  18.  useYarn,

  19.  useTypeScript,

  20.  webpack,

  21. });

  22. // Load proxy config

  23. const proxySetting = require(paths.appPackageJson).proxy;

  24. const proxyConfig = prepareProxy(proxySetting, paths.appPublic);

  25. // Serve webpack assets generated by the compiler over a web server.

  26. const serverConfig = createDevServerConfig(

  27.  proxyConfig,

  28.  urls.lanUrlForConfig

  29. );

  30. const devServer = new WebpackDevServer(compiler, serverConfig);

  31. // Launch WebpackDevServer.

  32. devServer.listen(port, HOST, err => {

  33.  if (err) {

  34.    return console.log(err);

  35.  }

  36.  if (isInteractive) {

  37.    clearConsole();

  38.  }


  39.  // We used to support resolving modules according to `NODE_PATH`.

  40.  // This now has been deprecated in favor of jsconfig/tsconfig.json

  41.  // This lets you use absolute paths in imports inside large monorepos:

  42.  if (process.env.NODE_PATH) {

  43.    console.log(

  44.      chalk.yellow(

  45.        '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.'

  46.      )

  47.    );

  48.    console.log();

  49.  }


  50.  console.log(chalk.cyan('Starting the development server...\n'));

  51.  openBrowser(urls.localUrlForBrowser);

  52. });


  53. ['SIGINT', 'SIGTERM'].forEach(function(sig) {

  54.  process.on(sig, function() {

  55.    devServer.close();

  56.    process.exit();

  57.  });

  58. });

经过 start命令的追踪,咱们知道CRA最终仍是经过WDS和webpack进行开发监听的,其实 build会比 start更简单,只是在webpack configuration中会进行优化。CRA作到了能够0配置,就能进行react项目的开发,调试,打包。

实际上是由于CRA把复杂的webpack config配置封装起来了,把babel plugins预设好了,把开发时会经常使用到的一个环境检查,polyfill兼容都给开发者作了,因此使用起来会比咱们直接使用webpack,本身进行重复的配置信息设置要来的简单不少。

相关文章
相关标签/搜索