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,本身進行重複的配置信息設置要來的簡單不少。

相關文章
相關標籤/搜索