【React】944- create-react-app初探
本文由?IMWeb?社區(qū) imweb.io 授權(quán)轉(zhuǎn)載自騰訊內(nèi)部 KM 論壇,原作者:kingfo。點(diǎn)擊閱讀原文查看 IMWeb 社區(qū)更多精彩文章。
create-react-app是一個(gè)react的cli腳手架+構(gòu)建器,我們可以基于CRA零配置直接上手開發(fā)一個(gè)react的SPA應(yīng)用。通過(guò)3種方式快速創(chuàng)建一個(gè)React SPA應(yīng)用:
npm init?with initializer (npm 6.1+)
npx?with generator (npm 5.2+)
yarn create?with initializer (yarn 0.25+)
例如我們新建一個(gè)叫my-app的SPA:
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通過(guò)添加參數(shù)生成ts支持:
npx create-react-app my-app --typescript # or yarn create react-app my-app --typescript當(dāng)然,如果我們是把一個(gè)CRA已經(jīng)生成的js項(xiàng)目改成支持ts,可以:
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即可。
CRA還能干嘛
CRA除了能幫我們構(gòu)建出一個(gè)React的SPA項(xiàng)目(generator),充當(dāng)腳手架的作用。還能為我們?cè)陧?xiàng)目開發(fā),編譯時(shí)進(jìn)行構(gòu)建,充當(dāng)builder的作用。可以看到生成的項(xiàng)目中的 package.json包含很多命令:
react-scripts start啟動(dòng)開發(fā)模式下的一個(gè)dev-server,并支持代碼修改時(shí)的?HotReload
react-scripts build使用webpack進(jìn)行編譯打包,生成生產(chǎn)模式下的所有腳本,靜態(tài)資源
react-scripts test執(zhí)行所有測(cè)試用例,完成對(duì)我們每個(gè)模塊質(zhì)量的保證
這里,我們針對(duì)start這條線進(jìn)行追蹤,探查CRA實(shí)現(xiàn)的原理。入口為 create-react-app/packages/react-scripts/bin/react-scripts.js,這個(gè)腳本會(huì)在react-scripts中設(shè)置到 package.json的bin字段中去,也就是說(shuō)這個(gè)package可以作為可執(zhí)行的nodejs腳本,通過(guò)cli方式在nodejs宿主環(huán)境中。這個(gè)入口腳本非常簡(jiǎn)單,這里只列出主要的一個(gè) 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; }可以看到,當(dāng)根據(jù)不同command,會(huì)分別resolve不同的js腳本,執(zhí)行不同的任務(wù),這里我們繼續(xù)看 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';因?yàn)槭情_發(fā)模式,所以這里把babel,node的環(huán)境變量都設(shè)置為 development,然后是全局錯(cuò)誤的捕獲,這些都是一個(gè)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; });確保其他的環(huán)境變量配置也讀進(jìn)進(jìn)程了,所以這里會(huì)通過(guò) ../config/env腳本進(jìn)行初始化:
// Ensure environment variables are read. require('../config/env');還有一些預(yù)檢查,這部分是作為eject之前對(duì)項(xiàng)目目錄的檢查,這里因?yàn)閑ject不在我們范圍,直接跳過(guò)。然后進(jìn)入到了我們主腳本的依賴列表:
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,可以大膽猜想原理和我們平時(shí)使用webpack并沒(méi)有什么不同。
因?yàn)?create-react-appmy-app之后通過(guò)模版生成的項(xiàng)目中入口腳本被放置在src/index.js,而入口html被放置在public/index.html,所以需要對(duì)這兩個(gè)文件進(jìn)行檢查:
// Warn and crash if required files are missing if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {process.exit(1); }下面這部分是涉及C9云部署時(shí)的環(huán)境變量檢查,不在我們考究范圍,也直接跳過(guò)。react-dev-utils/browsersHelper是一個(gè)瀏覽器支持的幫助utils,因?yàn)樵?react-scripts v2之后必須要提供一個(gè)browser list支持列表,不過(guò)我們可以在 package.json中看到,模版項(xiàng)目中已經(jīng)為我們生成了:
"browserslist": {"production": [">0.2%","not dead","not op_mini all"],"development": ["last 1 chrome version","last 1 firefox version","last 1 safari version"] }檢查完devServer端口后,進(jìn)入我們核心邏輯執(zhí)行,這里的主線還是和我們使用webpack方式幾乎沒(méi)什么區(qū)別,首先會(huì)通過(guò) configFactory創(chuàng)建出一個(gè)webpack的configuration object,然后通過(guò) createDevServerConfig創(chuàng)建出一個(gè)devServer的configuration object,然后傳遞webpack config實(shí)例化一個(gè)webpack compiler實(shí)例,傳遞devServer的configuration實(shí)例化一個(gè)WDS實(shí)例開始監(jiān)聽指定的端口,最后通過(guò)openBrowser調(diào)用我們的瀏覽器,打開我們的SPA。
其實(shí),整個(gè)流程我們看到這里,已經(jīng)結(jié)束了,我們知道WDS和webpack配合,可以進(jìn)行熱更,file changes watching等功能,我們開發(fā)時(shí),通過(guò)修改源代碼,或者樣式文件,會(huì)被實(shí)時(shí)監(jiān)聽,然后webpack中的HWR會(huì)實(shí)時(shí)刷新瀏覽器頁(yè)面,可以很方便的進(jìn)行實(shí)時(shí)調(diào)試開發(fā)。
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();}); });通過(guò) start命令的追蹤,我們知道CRA最終還是通過(guò)WDS和webpack進(jìn)行開發(fā)監(jiān)聽的,其實(shí) build會(huì)比 start更簡(jiǎn)單,只是在webpack configuration中會(huì)進(jìn)行優(yōu)化。CRA做到了可以0配置,就能進(jìn)行react項(xiàng)目的開發(fā),調(diào)試,打包。
其實(shí)是因?yàn)镃RA把復(fù)雜的webpack config配置封裝起來(lái)了,把babel plugins預(yù)設(shè)好了,把開發(fā)時(shí)會(huì)常用到的一個(gè)環(huán)境檢查,polyfill兼容都給開發(fā)者做了,所以使用起來(lái)會(huì)比我們直接使用webpack,自己進(jìn)行重復(fù)的配置信息設(shè)置要來(lái)的簡(jiǎn)單很多。
關(guān)注我們
IMWeb 團(tuán)隊(duì)隸屬騰訊公司,是國(guó)內(nèi)最專業(yè)的前端團(tuán)隊(duì)之一。
我們專注前端領(lǐng)域多年,負(fù)責(zé)過(guò) QQ 資料、QQ 注冊(cè)、QQ 群等億級(jí)業(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è)計(jì)模式 重溫系列(9篇全)
4.?正則 / 框架 / 算法等 重溫系列(16篇全)
5.?Webpack4 入門(上)||?Webpack4 入門(下)
6.?MobX 入門(上)?||??MobX 入門(下)
7. 120+篇原創(chuàng)系列匯總
回復(fù)“加群”與大佬們一起交流學(xué)習(xí)~
點(diǎn)擊“閱讀原文”查看 120+ 篇原創(chuàng)文章
總結(jié)
以上是生活随笔為你收集整理的【React】944- create-react-app初探的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 5G端到端网络切片技术与应用
- 下一篇: 使用 Paessler PRTG 进行应