阅读 806

create-react-app初探

本文作者: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,自己进行重复的配置信息设置要来的简单很多。

关注下面的标签,发现更多相似文章
评论