我正在使用一个由create-react-app
创建的大量Node包进行回购,所有这些包均由CI系统构建和测试。每个软件包的构建/测试(以react-scripts build
后跟react-scripts test --silent
完成)目前产生20行以上的输出,从而生成包含100行以上材料的构建日志,例如“ gzip之后的文件大小”和“在此处了解有关部署的更多信息”。这使得在该日志中查看错误消息,警告或其他问题变得更加困难。
是否有某种方法可以使我安静下来,而不必为每个软件包编写自己的自定义构建脚本(可能还有测试脚本)?如果我确实需要自定义脚本,那么,尽可能多地重用正在进行构建和测试的现有代码的最佳方法是什么?
答案 0 :(得分:4)
IOCP
从react-scripts build
程序包运行bin/react-scripts.js
,而该程序包基本上只是从同一程序包运行react-scripts
。
可悲的是,该scripts/build.js
脚本(无论如何,截至2018年10月15日)已被硬编码以调用诸如build.js
和printFileSizesAfterBuild()
之类的函数,而没有任何选择来禁用它们。因此,除了制作printHostingInstructions()
的副本,修改它以不打印不需要的东西并改用它之外,目前无法更改它。
@LukasGjetting有一个拉取请求PR #5429,用于向构建脚本添加build.js
选项。由于缺乏活动性,它已关闭,--silent
开发人员已在其他地方明确表示,他们不打算使create-react-app
非常可配置;他们建议的解决方案只是使用您自己的react-scripts
脚本。
答案 1 :(得分:0)
我自发地想到chalk。至少您可以对响应进行颜色编码。听起来好像尚未弹出您正在使用的应用程序。仅当退出应用程序时,您才能修改create-react-app
个基本文件。不幸的是,一旦弹出,您将无法反转效果。 Lmk是否有帮助
答案 2 :(得分:0)
如果您从应用程序根目录中的 /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"
}