User Guide – How to develop apps bootstrapped with Create React App.
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(htmlWebpackPlugin: HtmlWebpackPlugin, 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-webpack-plugin');var InterpolateHtmlPlugin =require('react-dev-utils/InterpolateHtmlPlugin');// webpack configvar publicUrl ='/my-custom-url';module.exports={ output:{ // ... publicPath: publicUrl +'/',}, // ... plugins: [ // Generates an `index.html` file with the <script> injected.newHtmlWebpackPlugin({ inject:true, template:path.resolve('public/index.html'),}), // Makes the public URL available as %PUBLIC_URL% in index.html, e.g.: // <link rel="icon" href="%PUBLIC_URL%/favicon.ico">newInterpolateHtmlPlugin(HtmlWebpackPlugin,{ PUBLIC_URL: publicUrl, // You can pass any key-value pairs, this was just an example. // WHATEVER: 42 will replace %WHATEVER% with 42 in index.html.}), // ... ], // ...};
new InlineChunkHtmlPlugin(htmlWebpackPlugin: HtmlWebpackPlugin, tests: Regex[])
This webpack plugin inlines script chunks into index.html.
It works in tandem with HtmlWebpackPlugin 4.x.
new ModuleScopePlugin(appSrc: string | string[], allowedFiles?: string[])
This webpack plugin ensures that relative imports from app's source directories don't reach outside of it.
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.
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.
clearConsole(): void
Clears the console, hopefully in a cross-platform way.
eslintFormatter(results: Object): string
This is our custom ESLint formatter that integrates well with Create React App console output.
You can use the default one instead if you prefer so.
Prints the JS and CSS asset sizes after the build, and includes a size comparison with previousFileSizes that were captured earlier using measureFileSizesBeforeBuild(). maxBundleGzipSize and maxChunkGzipSizemay may optionally be specified to display a warning when the main bundle or a chunk exceeds the specified size (in bytes).
On macOS, tries to find a known running editor process and opens the file in it. It can also be explicitly configured by REACT_EDITOR, VISUAL, or EDITOR environment variables. For example, you can put REACT_EDITOR=atom in your .env.local file, and Create React App will respect that.
Returns Express middleware that serves a ${servedPath}/service-worker.js that resets any previously set service worker configuration. Useful for development.
Returns Express middleware that redirects to ${servedPath}/${req.path}, if req.url does not start with servedPath. Useful for development.
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.
Prints hosting instructions after the project is built.
Pass your parsed package.json object as appPackage, your the URL where you plan to host the app as publicUrl, output.publicPath from your webpack configuration as publicPath, the buildFolder name, and whether to useYarn in instructions.
Returns a Promise resolving to either defaultPort or next available port if the user confirms it is okay to do. If the port is taken and the user has refused to use another port, or if the terminal is not interactive and can’t present user with the choice, resolves to null.
createCompiler(args: Object): WebpackCompiler
Creates a webpack compiler instance for WebpackDevServer with built-in helpful messages.
The args object accepts a number of properties:
appNamestring: The name that will be printed to the terminal.
configObject: The webpack configuration options to be provided to the webpack constructor.
devSocketObject: Required if useTypeScript is true. This object should include errors and warnings which are functions accepting an array of errors or warnings emitted by the type checking. This is useful when running fork-ts-checker-webpack-plugin with async: true to report errors that are emitted after the webpack build is complete.
urlsObject: To provide the urls argument, use prepareUrls() described below.
useYarnboolean: If true, yarn instructions will be emitted in the terminal instead of npm.
useTypeScriptboolean: If true, TypeScript type checking will be enabled. Be sure to provide the devSocket argument above if this is set to true.
tscCompileOnErrorboolean: If true, errors in TypeScript type checking will not prevent start script from running app, and will not cause build script to exit unsuccessfully. Also downgrades all TypeScript type checking error messages to warning messages.
webpackfunction: A reference to the webpack constructor.
Creates a class name for CSS Modules that uses either the filename or folder name if named index.module.css.
For MyFolder/MyComponent.module.css and class MyClass the output will be MyComponent.module_MyClass__[hash] For MyFolder/index.module.css and class MyClass the output will be MyFolder_MyClass__[hash]
var path = require('path');
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
// webpack config
module.exports = {
// ...
plugins: [
// ...
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebook/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(path.resolve('node_modules')),
],
// ...
};
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);
}
var clearConsole = require('react-dev-utils/clearConsole');
clearConsole();
console.log('Just cleared the screen!');
create-react-app
in /Users/developer/create-react-app
var getProcessForPort = require('react-dev-utils/getProcessForPort');
getProcessForPort(3000);
var path = require('path');
var openBrowser = require('react-dev-utils/openBrowser');
if (openBrowser('http://localhost:3000')) {
console.log('The browser tab has been opened!');
}
// webpack development config
module.exports = {
// ...
entry: [
// You can replace the line below with these two lines if you prefer the
// stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
'react-dev-utils/webpackHotDevClient',
'src/index',
],
// ...
};