开发react 应用最好用的脚手架 create-react-app

 

安装


npx create-react-app my-app
cd my-app
npm start

7897174ffc090643661074e6cb0c5364a1d962ad
安装后之后,就是这样的了
e238253780b8d3af4894c0266ff3fcb699b12d27

配置

这样的”零配置”没法满足我们的需求,我们需要自定义,需要加一些 loader,plugin 等。
react 团队当然也提供了这样的途径

 

yarn eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

执行 yarn eject (这是一个不可逆操作)

这个命令将部分配置文件释放出来,目录结构就变成下面这样子了

8e983047d466fd5fa2214a043eff66588372b95a

这时候就能够对 webpack.config 进行配置了,不过有的同学也会发现,package.json script 中并没有发现 webpack -c config.js 类似的命令,也没有看到.eslintrc.babelrc 等配置文件。

不过 package.json->script 中能看到 这三条命令

 

"start": "node scripts/start.js",
"build": "node scripts/build.js",
"test": "node scripts/test.js --env=jsdom"

打开用户开发环境的 start.js 看看
片段:

 

// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
  .then(port => {
    if (port == null) {
      // We have not found a port.
      return;
    }
    const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
    const appName = require(paths.appPackageJson).name;
    const urls = prepareUrls(protocol, HOST, port);
    // Create a webpack compiler that is configured with custom messages.
    const compiler = createCompiler(webpack, config, appName, urls, useYarn);
    // 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 sever.
    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();
      }
      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();
      });
    });
  })
  .catch(err => {
    if (err && err.message) {
      console.log(err.message);
    }
    process.exit(1);
  });

在 start.js 中通过代码来启动 webpack 以及 DevServer
eslint 和 babel 的配置 写在了 package.json 里

 

"babel": {
  "presets": [
    "react-app"
  ]
},
"eslintConfig": {
  "extends": "react-app"
},

能中 dependencies 中找到对应的两个库 babel-preset-react-appeslint-config-react-app

查看babel-preset-react-app源码,就能看到具体的 babel 配置了(eslint-config-react-app 同理),对这一块不熟悉的同学可以看看怎样组合 presets plugin 和 polyfill 的( ps:经常看到网上很多人贴出来的配置 会打包一大堆不需要的 polyfill )

3635c493fc35c6cca925a4a4febcdccccec72d0e

 

posted @ 2018-12-18 20:09  燕十三丶  阅读(592)  评论(0编辑  收藏  举报
AmazingCounters.com