What is react-dev-utils?
The react-dev-utils package provides a set of utilities designed to enhance the development experience of building React applications, especially when used in conjunction with Create React App. These utilities include webpack configuration helpers, development server helpers, and an assortment of other small utilities designed to make common tasks more convenient.
What are react-dev-utils's main functionalities?
Interacting with Webpack
This feature allows developers to interact with Webpack more easily, for example, by choosing a port for the development server. The code sample demonstrates how to use the `choosePort` function to select a port for running the development server.
const { choosePort } = require('react-dev-utils/WebpackDevServerUtils');
choosePort('localhost', 3000).then(port => console.log(`Port selected: ${port}`));
Formatting Webpack Messages
This utility helps in formatting the output of Webpack messages to be more readable. The code sample shows how to format raw Webpack messages into a more digestible format, separating out errors and warnings.
const { formatWebpackMessages } = require('react-dev-utils/formatWebpackMessages');
const rawMessages = webpackCompiler.run();
const messages = formatWebpackMessages(rawMessages);
console.log(messages.errors); console.log(messages.warnings);
Opening Browser
This feature provides a simple way to programmatically open the developer's browser to a specified URL, which is particularly useful when starting a development server. The code sample demonstrates opening the default browser to 'http://localhost:3000'.
const { openBrowser } = require('react-dev-utils/openBrowser');
openBrowser('http://localhost:3000');
Other packages similar to react-dev-utils
webpack-dev-server
Similar to some functionalities provided by react-dev-utils, webpack-dev-server offers a development server that provides live reloading. It is more focused on being a standalone server for webpack projects, whereas react-dev-utils offers utilities that are more specifically tailored to React applications and can be used in conjunction with webpack-dev-server.
env-cmd
This package allows you to specify and manage environment variables for your development environment, similar to how react-dev-utils allows for environment variable manipulation and other configuration tweaks. However, env-cmd is more focused on environment variables and does not offer the wide range of utilities related to webpack and development server management.
cross-env
Cross-env provides a cross-platform way to set and use environment variables in npm scripts, which is a narrower scope compared to react-dev-utils. While react-dev-utils includes utilities for working with environment variables among its features, cross-env is specifically designed for this purpose and does not include the broader set of development utilities.
react-dev-utils
This package includes some utilities used by Create React App.
Please refer to its documentation:
Usage in Create React App Projects
These utilities come by default with Create React App, which includes it by default. You don’t need to install it separately in Create React App projects.
Usage Outside of Create React App
If you don’t use Create React App, or if you ejected, you may keep using these utilities. Their development will be aligned with Create React App, so major versions of these utilities may come out relatively often. Feel free to fork or copy and paste them into your projects if you’d like to have more control over them, or feel free to use the old versions. Not all of them are React-specific, but we might make some of them more React-specific in the future.
Entry Points
There is no single entry point. You can only import individual top-level modules.
new InterpolateHtmlPlugin(replacements: {[key:string]: string})
This Webpack plugin lets us interpolate custom variables into index.html
.
It works in tandem with HtmlWebpackPlugin 2.x via its events.
var path = require('path');
var HtmlWebpackPlugin = require('html-dev-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var publicUrl = '/my-custom-url';
module.exports = {
output: {
publicPath: publicUrl + '/'
},
plugins: [
new InterpolateHtmlPlugin({
PUBLIC_URL: publicUrl
}),
new HtmlWebpackPlugin({
inject: true,
template: path.resolve('public/index.html'),
}),
],
}
new WatchMissingNodeModulesPlugin(nodeModulesPath: string)
This Webpack plugin ensures npm install <library>
forces a project rebuild.
We’re not sure why this isn't Webpack's default behavior.
See #186 for details.
var path = require('path');
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
module.exports = {
plugins: [
new WatchMissingNodeModulesPlugin(path.resolve('node_modules'))
],
}
checkRequiredFiles(files: Array<string>): boolean
Makes sure that all passed files exist.
Filenames are expected to be absolute.
If a file is not found, prints a warning message and returns false
.
var path = require('path');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
if (!checkRequiredFiles([
path.resolve('public/index.html'),
path.resolve('src/index.js')
])) {
process.exit(1);
}
clearConsole(): void
Clears the console, hopefully in a cross-platform way.
var clearConsole = require('react-dev-utils/clearConsole');
clearConsole();
console.log('Just cleared the screen!');
formatWebpackMessages(stats: WebpackStats): {errors: Array<string>, warnings: Array<string>}
Extracts and prettifies warning and error messages from webpack stats object.
var webpack = require('webpack');
var config = require('../config/webpack.config.dev');
var compiler = webpack(config);
compiler.plugin('invalid', function() {
console.log('Compiling...');
});
compiler.plugin('done', function(stats) {
var messages = formatWebpackMessages(stats);
if (!messages.errors.length && !messages.warnings.length) {
console.log('Compiled successfully!');
}
if (messages.errors.length) {
console.log('Failed to compile.');
messages.errors.forEach(console.log);
return;
}
if (messages.warnings.length) {
console.log('Compiled with warnings.');
messages.warnings.forEach(console.log);
}
});
openBrowser(url: string): boolean
Attempts to open the browser with a given URL.
On Mac OS X, attempts to reuse an existing Chrome tab via AppleScript.
Otherwise, falls back to opn behavior.
var path = require('path');
var openBrowser = require('react-dev-utils/openBrowser');
if (openBrowser('http://localhost:3000')) {
console.log('The browser tab has been opened!');
}
prompt(message: string, isYesDefault: boolean): Promise<boolean>
This function displays a console prompt to the user.
By convention, "no" should be the conservative choice.
If you mistype the answer, we'll always take it as a "no".
You can control the behavior on <Enter>
with isYesDefault
.
var prompt = require('react-dev-utils/prompt');
prompt(
'Are you sure you want to eat all the candy?',
false
).then(shouldEat => {
if (shouldEat) {
console.log('You have successfully consumed all the candy.');
} else {
console.log('Phew, candy is still available!');
}
});