create-react-app初探

騰訊IMWeb團隊發表於2019-08-12

本文作者:IMWeb IMWeb團隊 原文出處:IMWeb社群 未經同意,禁止轉載

create-react-app是一個react的cli腳手架+構建器,我們可以基於CRA零配置直接上手開發一個react的SPA應用。 通過3種方式快速建立一個React SPA應用:

  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:

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支援:

npx create-react-app my-app --typescript
# or
yarn create react-app my-app --typescript
複製程式碼

當然,如果我們是把一個CRA已經生成的js專案改成支援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除了能幫我們構建出一個React的SPA專案(generator),充當腳手架的作用。還能為我們在專案開發,編譯時進行構建,充當builder的作用。可以看到生成的專案中的package.json包含很多命令:

  1. react-scripts start啟動開發模式下的一個dev-server,並支援程式碼修改時的Hot Reload
  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不在我們範圍,直接跳過。然後進入到了我們主指令碼的依賴列表:

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,自己進行重複的配置資訊設定要來的簡單很多。

相關文章