<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          【React】944- create-react-app初探

          共 7901字,需瀏覽 16分鐘

           ·

          2021-05-05 09:26

          本文由 IMWeb 社區(qū) imweb.io 授權(quán)轉(zhuǎn)載自騰訊內(nèi)部 KM 論壇,原作者:kingfo。點擊閱讀原文查看 IMWeb 社區(qū)更多精彩文章。

          create-react-app是一個react的cli腳手架+構(gòu)建器,我們可以基于CRA零配置直接上手開發(fā)一個react的SPA應(yīng)用。通過3種方式快速創(chuàng)建一個React SPA應(yīng)用:

          1. npm init with initializer (npm 6.1+)

          2. npx with generator (npm 5.2+)

          3. yarn create with initializer (yarn 0.25+)

          例如我們新建一個叫my-app的SPA:

          1. my-app

          2. ├── README.md

          3. ├── node_modules

          4. ├── package.json

          5. ├── .gitignore

          6. ├── public

          7. ├── favicon.ico

          8. ├── index.html

          9. └── manifest.json

          10. └── src

          11. ├── App.css

          12. ├── App.js

          13. ├── App.test.js

          14. ├── index.css

          15. ├── index.js

          16. ├── logo.svg

          17. └── serviceWorker.js

          通過添加參數(shù)生成ts支持:

          1. npx create-react-app my-app --typescript

          2. # or

          3. yarn create react-app my-app --typescript

          當(dāng)然,如果我們是把一個CRA已經(jīng)生成的js項目改成支持ts,可以:

          1. npm install --save typescript @types/node @types/react @types/react-dom @types/jest

          2. # or

          3. yarn add typescript @types/node @types/react @types/react-dom @types/jest

          然后,將.js文件后綴改成.ts重啟development server即可。

          CRA還能干嘛

          CRA除了能幫我們構(gòu)建出一個React的SPA項目(generator),充當(dāng)腳手架的作用。還能為我們在項目開發(fā),編譯時進行構(gòu)建,充當(dāng)builder的作用。可以看到生成的項目中的 package.json包含很多命令:

          1. react-scripts start啟動開發(fā)模式下的一個dev-server,并支持代碼修改時的 HotReload

          2. react-scripts build使用webpack進行編譯打包,生成生產(chǎn)模式下的所有腳本,靜態(tài)資源

          3. react-scripts test執(zhí)行所有測試用例,完成對我們每個模塊質(zhì)量的保證

          這里,我們針對start這條線進行追蹤,探查CRA實現(xiàn)的原理。入口為 create-react-app/packages/react-scripts/bin/react-scripts.js,這個腳本會在react-scripts中設(shè)置到 package.json的bin字段中去,也就是說這個package可以作為可執(zhí)行的nodejs腳本,通過cli方式在nodejs宿主環(huán)境中。這個入口腳本非常簡單,這里只列出主要的一個 switch分支:

          1. switch (script) {

          2. case 'build':

          3. case 'eject':

          4. case 'start':

          5. case 'test': {

          6. const result = spawn.sync(

          7. 'node',

          8. nodeArgs

          9. .concat(require.resolve('../scripts/' + script))

          10. .concat(args.slice(scriptIndex + 1)),

          11. { stdio: 'inherit' }

          12. );

          13. if (result.signal) {

          14. if (result.signal === 'SIGKILL') {

          15. console.log(

          16. 'The build failed because the process exited too early. ' +

          17. 'This probably means the system ran out of memory or someone called ' +

          18. '`kill -9` on the process.'

          19. );

          20. } else if (result.signal === 'SIGTERM') {

          21. console.log(

          22. 'The build failed because the process exited too early. ' +

          23. 'Someone might have called `kill` or `killall`, or the system could ' +

          24. 'be shutting down.'

          25. );

          26. }

          27. process.exit(1);

          28. }

          29. process.exit(result.status);

          30. break;

          31. }

          32. default:

          33. console.log('Unknown script "' + script + '".');

          34. console.log('Perhaps you need to update react-scripts?');

          35. console.log(

          36. 'See: https://facebook.github.io/create-react-app/docs/updating-to-new-releases'

          37. );

          38. break;

          39. }

          可以看到,當(dāng)根據(jù)不同command,會分別resolve不同的js腳本,執(zhí)行不同的任務(wù),這里我們繼續(xù)看 require('../scripts/start')

          1. // Do this as the first thing so that any code reading it knows the right env.

          2. process.env.BABEL_ENV = 'development';

          3. process.env.NODE_ENV = 'development';

          因為是開發(fā)模式,所以這里把babel,node的環(huán)境變量都設(shè)置為 development,然后是全局錯誤的捕獲,這些都是一個cli腳本通常的處理方式:

          1. // Makes the script crash on unhandled rejections instead of silently

          2. // ignoring them. In the future, promise rejections that are not handled will

          3. // terminate the Node.js process with a non-zero exit code.

          4. process.on('unhandledRejection', err => {

          5. throw err;

          6. });

          確保其他的環(huán)境變量配置也讀進進程了,所以這里會通過 ../config/env腳本進行初始化:

          1. // Ensure environment variables are read.

          2. require('../config/env');

          還有一些預(yù)檢查,這部分是作為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,所以需要對這兩個文件進行檢查:

          1. // Warn and crash if required files are missing

          2. if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {

          3. process.exit(1);

          4. }

          下面這部分是涉及C9云部署時的環(huán)境變量檢查,不在我們考究范圍,也直接跳過。react-dev-utils/browsersHelper是一個瀏覽器支持的幫助utils,因為在 react-scripts v2之后必須要提供一個browser list支持列表,不過我們可以在 package.json中看到,模版項目中已經(jīng)為我們生成了:

          1. "browserslist": {

          2. "production": [

          3. ">0.2%",

          4. "not dead",

          5. "not op_mini all"

          6. ],

          7. "development": [

          8. "last 1 chrome version",

          9. "last 1 firefox version",

          10. "last 1 safari version"

          11. ]

          12. }

          檢查完devServer端口后,進入我們核心邏輯執(zhí)行,這里的主線還是和我們使用webpack方式幾乎沒什么區(qū)別,首先會通過 configFactory創(chuàng)建出一個webpack的configuration object,然后通過 createDevServerConfig創(chuàng)建出一個devServer的configuration object,然后傳遞webpack config實例化一個webpack compiler實例,傳遞devServer的configuration實例化一個WDS實例開始監(jiān)聽指定的端口,最后通過openBrowser調(diào)用我們的瀏覽器,打開我們的SPA。

          其實,整個流程我們看到這里,已經(jīng)結(jié)束了,我們知道WDS和webpack配合,可以進行熱更,file changes watching等功能,我們開發(fā)時,通過修改源代碼,或者樣式文件,會被實時監(jiān)聽,然后webpack中的HWR會實時刷新瀏覽器頁面,可以很方便的進行實時調(diào)試開發(fā)。

          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進行開發(fā)監(jiān)聽的,其實 build會比 start更簡單,只是在webpack configuration中會進行優(yōu)化。CRA做到了可以0配置,就能進行react項目的開發(fā),調(diào)試,打包。

          其實是因為CRA把復(fù)雜的webpack config配置封裝起來了,把babel plugins預(yù)設(shè)好了,把開發(fā)時會常用到的一個環(huán)境檢查,polyfill兼容都給開發(fā)者做了,所以使用起來會比我們直接使用webpack,自己進行重復(fù)的配置信息設(shè)置要來的簡單很多。


          關(guān)注我們

          IMWeb 團隊隸屬騰訊公司,是國內(nèi)最專業(yè)的前端團隊之一。

          我們專注前端領(lǐng)域多年,負(fù)責(zé)過 QQ 資料、QQ 注冊、QQ 群等億級業(yè)務(wù)。目前聚焦于在線教育領(lǐng)域,精心打磨 騰訊課堂、企鵝輔導(dǎo) 及 ABCMouse 三大產(chǎn)品。

          社區(qū)官網(wǎng)

          http://imweb.io/

          加入我們

          https://hr.tencent.com/position_detail.php?id=45616


          1. JavaScript 重溫系列(22篇全)
          2. ECMAScript 重溫系列(10篇全)
          3. JavaScript設(shè)計模式 重溫系列(9篇全)
          4. 正則 / 框架 / 算法等 重溫系列(16篇全)
          5. Webpack4 入門(上)|| Webpack4 入門(下)
          6. MobX 入門(上) ||  MobX 入門(下)
          7. 120+篇原創(chuàng)系列匯總

          回復(fù)“加群”與大佬們一起交流學(xué)習(xí)~

          點擊“閱讀原文”查看 120+ 篇原創(chuàng)文章

          瀏覽 62
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  精品久久久麻豆 | 俺也去成人视频 | 超碰无码人妻 | 亚洲视频无码在线 | 我爱婷婷五月天 |