6

我正在处理一个包含许多使用 . 创建的 Node 包的存储库create-react-app,所有这些包都是由 CI 系统构建和测试的。每个包的构建/测试,react-scripts build由完成react-scripts test --silent,当前产生超过 20 行输出,生成一个包含超过 100 行材料的构建日志,例如“gzip 后的文件大小”和“在此处了解有关部署的更多信息”。这使得在该日志中查看错误消息、警告或其他问题变得更加困难。

除了为每个软件包编写我自己的自定义构建脚本(也可能还有测试脚本)之外,有什么方法可以让我平静下来吗?如果我确实需要自定义脚本,那么尽可能多地重用正在进行构建和测试的现有代码的最佳方法是什么?

4

3 回答 3

6

react-scripts build从基本上只是从同一个包运行bin/react-scripts.js的包中运行。react-scriptsscripts/build.js

可悲的是,该build.js脚本(无论如何,截至 2018 年 10 月 15 日)被硬编码为调用诸如printFileSizesAfterBuild()and之类的函数printHostingInstructions(),而没有任何禁用这些函数的选项。所以目前没有办法改变它,除了制作一个副本build.js,修改它不打印你不想要的东西,而是使用它。

@LukasGjetting有一个PR #5429的拉取请求,--silent用于向构建脚本添加一个选项。由于缺乏活动,它已经关闭,create-react-app开发人员在其他地方已经非常清楚地表明他们不打算进行react-scripts非常可配置的操作;他们建议的解决方案就是使用您自己的build.js脚本。

于 2018-10-15T04:30:21.110 回答
1

如果您从/node_modules/react-scripts/scripts/build.js应用程序的根目录中复制 build.js 脚本,请使路径相对于 aconst basepath = __dirname+'/node_modules/react-scripts/scripts/' 并消除不必要的日志。package.json将脚本构建调整为:node build 并且您的反应应用程序构建非常安静:)

示例构建脚本:

// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
// @remove-on-eject-end
'use strict';

// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
const basepath = __dirname + '/node_modules/react-scripts/scripts/';
// 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;
});

// Ensure environment variables are read.
require(basepath + '../config/env');
// @remove-on-eject-begin
// Do the preflight checks (only happens before eject).
const verifyPackageTree = require(basepath + 'utils/verifyPackageTree');
if (process.env.SKIP_PREFLIGHT_CHECK !== 'true') {
  verifyPackageTree();
}
const verifyTypeScriptSetup = require(basepath + 'utils/verifyTypeScriptSetup');
verifyTypeScriptSetup();
// @remove-on-eject-end

const path = require('path');
const chalk = require('react-dev-utils/chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const configFactory = require(basepath + '../config/webpack.config');
const paths = require(basepath + '../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');

const measureFileSizesBeforeBuild =
  FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);

// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;

const isInteractive = process.stdout.isTTY;

// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1);
}

// Generate configuration
const config = configFactory('production');

// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const {
  checkBrowsers
} = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
  .then(() => {
    // First, read the current file sizes in build directory.
    // This lets us display how much they changed later.
    return measureFileSizesBeforeBuild(paths.appBuild);
  })
  .then(previousFileSizes => {
    // Remove all content but keep the directory so that
    // if you're in it, you don't end up in Trash
    fs.emptyDirSync(paths.appBuild);
    // Merge with the public folder
    copyPublicFolder();
    // Start the webpack build
    return build(previousFileSizes);
  })
  .then(
    ({
      stats,
      previousFileSizes,
      warnings
    }) => {
      // if (warnings.length) {
      //   console.log(chalk.yellow('Compiled with warnings.\n'));
      //   console.log(warnings.join('\n\n'));
      //   console.log(
      //     '\nSearch for the ' +
      //       chalk.underline(chalk.yellow('keywords')) +
      //       ' to learn more about each warning.'
      //   );
      //   console.log(
      //     'To ignore, add ' +
      //       chalk.cyan('// eslint-disable-next-line') +
      //       ' to the line before.\n'
      //   );
      // } else {
      //   console.log(chalk.green('Compiled successfully.\n'));
      // }
      //
      // console.log('File sizes after gzip:\n');
      // printFileSizesAfterBuild(
      //   stats,
      //   previousFileSizes,
      //   paths.appBuild,
      //   WARN_AFTER_BUNDLE_GZIP_SIZE,
      //   WARN_AFTER_CHUNK_GZIP_SIZE
      // );
      // console.log();
      console.log(chalk.green('Compiled successfully.\n'));

      const appPackage = require(paths.appPackageJson);
      const publicUrl = paths.publicUrlOrPath;
      const publicPath = config.output.publicPath;
      const buildFolder = path.relative(process.cwd(), paths.appBuild);
      // printHostingInstructions(
      //   appPackage,
      //   publicUrl,
      //   publicPath,
      //   buildFolder,
      //   useYarn
      // );
    },
    err => {
      const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
      if (tscCompileOnError) {
        console.log(
          chalk.yellow(
            'Compiled with the following type errors (you may want to check these before deploying your app):\n'
          )
        );
        printBuildError(err);
      } else {
        console.log(chalk.red('Failed to compile.\n'));
        printBuildError(err);
        process.exit(1);
      }
    }
  )
  .catch(err => {
    if (err && err.message) {
      console.log(err.message);
    }
    process.exit(1);
  });

// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
  // 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();
  }


  const compiler = webpack(config);
  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      let messages;
      if (err) {
        if (!err.message) {
          return reject(err);
        }

        let errMessage = err.message;

        // Add additional information for postcss errors
        if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) {
          errMessage +=
            '\nCompileError: Begins at CSS selector ' +
            err['postcssNode'].selector;
        }

        messages = formatWebpackMessages({
          errors: [errMessage],
          warnings: [],
        });
      } else {
        messages = formatWebpackMessages(
          stats.toJson({
            all: false,
            warnings: true,
            errors: true
          })
        );
      }
      if (messages.errors.length) {
        // Only keep the first error. Others are often indicative
        // of the same problem, but confuse the reader with noise.
        if (messages.errors.length > 1) {
          messages.errors.length = 1;
        }
        return reject(new Error(messages.errors.join('\n\n')));
      }
      if (
        process.env.CI &&
        (typeof process.env.CI !== 'string' ||
          process.env.CI.toLowerCase() !== 'false') &&
        messages.warnings.length
      ) {
        console.log(
          chalk.yellow(
            '\nTreating warnings as errors because process.env.CI = true.\n' +
            'Most CI servers set it automatically.\n'
          )
        );
        return reject(new Error(messages.warnings.join('\n\n')));
      }

      return resolve({
        stats,
        previousFileSizes,
        warnings: messages.warnings,
      });
    });
  });
}

function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
    filter: file => file !== paths.appHtml,
  });
}

和示例 package.json 脚本选项:

"scripts": {
  "start": "react-scripts start", "build": "node build"
}
于 2021-02-11T15:01:26.197 回答
0

我自发地想到了粉笔。至少您可以对响应进行颜色编码。听起来您正在使用的应用程序尚未(尚未)弹出。只有在弹出应用程序时,您才能修改create-react-app基础文件。不幸的是,一旦弹出,您就无法逆转效果。Lmk 如果有帮助

于 2018-10-15T04:41:47.117 回答