我怎样才能让 `react-scripts build` 安静下来?
How can I make `react-scripts build` quiet?
我正在使用一个 repo,其中包含许多使用 create-react-app
创建的 Node 包,所有这些包都是由 CI 系统构建和测试的。每个包的 build/test,完成 react-scripts build
后跟 react-scripts test --silent
,目前正在生成超过 20 行的输出,导致构建日志包含超过 100 行 material,例如"File sizes after gzip" 和 "Find out more about deployment here." 这使得在该日志中更难看到错误消息、警告或其他问题。
除了为每个包编写我自己的自定义构建脚本(也可能是测试脚本)之外,有什么方法可以让我安静下来吗?如果我确实需要自定义脚本,那么尽可能多地重用正在进行构建和测试的现有代码的最佳方法是什么?
react-scripts build
从 react-scripts
包中运行 bin/react-scripts.js
,基本上只从同一个包中运行 scripts/build.js
。
可悲的是,build.js
脚本(从 2018 年 10 月 15 日起)被硬编码为调用 printFileSizesAfterBuild()
和 printHostingInstructions()
等函数,没有任何选项禁用这些。所以目前没有办法改变这个,除了复制build.js
,修改它不打印你不想要的东西,而是使用它。
来自@LukasGjetting 的拉取请求 PR #5429 向构建脚本添加 --silent
选项。由于缺乏活动,它已经关闭,create-react-app
开发人员在其他地方已经非常清楚地表明他们不打算使 react-scripts
非常可配置;他们建议的解决方案是使用您自己的 build.js
脚本。
我不由自主地想到了 chalk。至少您可以对响应进行颜色编码。听起来您正在使用的应用程序尚未(尚未)弹出。只有在弹出应用程序时,您才能修改 create-react-app
个基础文件。不幸的是,一旦弹出,您将无法逆转效果。 Lmk 如果有帮助
如果您从应用程序根目录中的 /node_modules/react-scripts/scripts/build.js
复制 build.js 脚本,请使路径相对于 const basepath = __dirname+'/node_modules/react-scripts/scripts/'
并删除不必要的日志。
将 package.json
脚本构建调整为:node build
而且你有一个非常安静的 React 应用构建 :)
示例构建脚本:
// @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"
}
我正在使用一个 repo,其中包含许多使用 create-react-app
创建的 Node 包,所有这些包都是由 CI 系统构建和测试的。每个包的 build/test,完成 react-scripts build
后跟 react-scripts test --silent
,目前正在生成超过 20 行的输出,导致构建日志包含超过 100 行 material,例如"File sizes after gzip" 和 "Find out more about deployment here." 这使得在该日志中更难看到错误消息、警告或其他问题。
除了为每个包编写我自己的自定义构建脚本(也可能是测试脚本)之外,有什么方法可以让我安静下来吗?如果我确实需要自定义脚本,那么尽可能多地重用正在进行构建和测试的现有代码的最佳方法是什么?
react-scripts build
从 react-scripts
包中运行 bin/react-scripts.js
,基本上只从同一个包中运行 scripts/build.js
。
可悲的是,build.js
脚本(从 2018 年 10 月 15 日起)被硬编码为调用 printFileSizesAfterBuild()
和 printHostingInstructions()
等函数,没有任何选项禁用这些。所以目前没有办法改变这个,除了复制build.js
,修改它不打印你不想要的东西,而是使用它。
来自@LukasGjetting 的拉取请求 PR #5429 向构建脚本添加 --silent
选项。由于缺乏活动,它已经关闭,create-react-app
开发人员在其他地方已经非常清楚地表明他们不打算使 react-scripts
非常可配置;他们建议的解决方案是使用您自己的 build.js
脚本。
我不由自主地想到了 chalk。至少您可以对响应进行颜色编码。听起来您正在使用的应用程序尚未(尚未)弹出。只有在弹出应用程序时,您才能修改 create-react-app
个基础文件。不幸的是,一旦弹出,您将无法逆转效果。 Lmk 如果有帮助
如果您从应用程序根目录中的 /node_modules/react-scripts/scripts/build.js
复制 build.js 脚本,请使路径相对于 const basepath = __dirname+'/node_modules/react-scripts/scripts/'
并删除不必要的日志。
将 package.json
脚本构建调整为:node build
而且你有一个非常安静的 React 应用构建 :)
示例构建脚本:
// @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"
}