UNPKG

11.5 kBMarkdownView Raw
1# react-dev-utils
2
3This package includes some utilities used by [Create React App](https://github.com/facebookincubator/create-react-app).<br>
4Please refer to its documentation:
5
6* [Getting Started](https://github.com/facebookincubator/create-react-app/blob/master/README.md#getting-started) – How to create a new app.
7* [User Guide](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md) – How to develop apps bootstrapped with Create React App.
8
9## Usage in Create React App Projects
10
11These utilities come by default with [Create React App](https://github.com/facebookincubator/create-react-app), which includes it by default. **You don’t need to install it separately in Create React App projects.**
12
13## Usage Outside of Create React App
14
15If you don’t use Create React App, or if you [ejected](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#npm-run-eject), 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.
16
17### Entry Points
18
19There is no single entry point. You can only import individual top-level modules.
20
21#### `new InterpolateHtmlPlugin(replacements: {[key:string]: string})`
22
23This Webpack plugin lets us interpolate custom variables into `index.html`.<br>
24It works in tandem with [HtmlWebpackPlugin](https://github.com/ampedandwired/html-webpack-plugin) 2.x via its [events](https://github.com/ampedandwired/html-webpack-plugin#events).
25
26```js
27var path = require('path');
28var HtmlWebpackPlugin = require('html-dev-plugin');
29var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
30
31// Webpack config
32var publicUrl = '/my-custom-url';
33
34module.exports = {
35 output: {
36 // ...
37 publicPath: publicUrl + '/'
38 },
39 // ...
40 plugins: [
41 // Makes the public URL available as %PUBLIC_URL% in index.html, e.g.:
42 // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
43 new InterpolateHtmlPlugin({
44 PUBLIC_URL: publicUrl
45 // You can pass any key-value pairs, this was just an example.
46 // WHATEVER: 42 will replace %WHATEVER% with 42 in index.html.
47 }),
48 // Generates an `index.html` file with the <script> injected.
49 new HtmlWebpackPlugin({
50 inject: true,
51 template: path.resolve('public/index.html'),
52 }),
53 // ...
54 ],
55 // ...
56}
57```
58
59
60#### `new ModuleScopePlugin(appSrc: string, allowedFiles?: string[])`
61
62This Webpack plugin ensures that relative imports from app's source directory don't reach outside of it.
63
64```js
65var path = require('path');
66var ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
67
68
69module.exports = {
70 // ...
71 resolve: {
72 // ...
73 plugins: [
74 new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
75 // ...
76 ],
77 // ...
78 },
79 // ...
80}
81```
82
83#### `new WatchMissingNodeModulesPlugin(nodeModulesPath: string)`
84
85This Webpack plugin ensures `npm install <library>` forces a project rebuild.<br>
86We’re not sure why this isn't Webpack's default behavior.<br>
87See [#186](https://github.com/facebookincubator/create-react-app/issues/186) for details.
88
89```js
90var path = require('path');
91var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
92
93// Webpack config
94module.exports = {
95 // ...
96 plugins: [
97 // ...
98 // If you require a missing module and then `npm install` it, you still have
99 // to restart the development server for Webpack to discover it. This plugin
100 // makes the discovery automatic so you don't have to restart.
101 // See https://github.com/facebookincubator/create-react-app/issues/186
102 new WatchMissingNodeModulesPlugin(path.resolve('node_modules'))
103 ],
104 // ...
105}
106```
107
108#### `checkRequiredFiles(files: Array<string>): boolean`
109
110Makes sure that all passed files exist.<br>
111Filenames are expected to be absolute.<br>
112If a file is not found, prints a warning message and returns `false`.
113
114```js
115var path = require('path');
116var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
117
118if (!checkRequiredFiles([
119 path.resolve('public/index.html'),
120 path.resolve('src/index.js')
121])) {
122 process.exit(1);
123}
124```
125
126#### `clearConsole(): void`
127
128Clears the console, hopefully in a cross-platform way.
129
130```js
131var clearConsole = require('react-dev-utils/clearConsole');
132
133clearConsole();
134console.log('Just cleared the screen!');
135```
136
137#### `eslintFormatter(results: Object): string`
138
139This is our custom ESLint formatter that integrates well with Create React App console output.<br>
140You can use the default one instead if you prefer so.
141
142```js
143const eslintFormatter = require('react-dev-utils/eslintFormatter');
144
145// In your webpack config:
146// ...
147module: {
148 rules: [
149 {
150 test: /\.(js|jsx)$/,
151 include: paths.appSrc,
152 enforce: 'pre',
153 use: [
154 {
155 loader: 'eslint-loader',
156 options: {
157 // Pass the formatter:
158 formatter: eslintFormatter,
159 },
160 },
161 ],
162 }
163 ]
164}
165```
166
167#### `FileSizeReporter`
168
169##### `measureFileSizesBeforeBuild(buildFolder: string): Promise<OpaqueFileSizes>`
170
171Captures JS and CSS asset sizes inside the passed `buildFolder`. Save the result value to compare it after the build.
172
173##### `printFileSizesAfterBuild(webpackStats: WebpackStats, previousFileSizes: OpaqueFileSizes, buildFolder: string, maxBundleGzipSize?: number, maxChunkGzipSize?: number)`
174
175Prints 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).
176
177```js
178var {
179 measureFileSizesBeforeBuild,
180 printFileSizesAfterBuild,
181} = require('react-dev-utils/FileSizeReporter');
182
183measureFileSizesBeforeBuild(buildFolder).then(previousFileSizes => {
184 return cleanAndRebuild().then(webpackStats => {
185 printFileSizesAfterBuild(webpackStats, previousFileSizes, buildFolder);
186 });
187});
188```
189
190#### `formatWebpackMessages({errors: Array<string>, warnings: Array<string>}): {errors: Array<string>, warnings: Array<string>}`
191
192Extracts and prettifies warning and error messages from webpack [stats](https://github.com/webpack/docs/wiki/node.js-api#stats) object.
193
194```js
195var webpack = require('webpack');
196var config = require('../config/webpack.config.dev');
197var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
198
199var compiler = webpack(config);
200
201compiler.plugin('invalid', function() {
202 console.log('Compiling...');
203});
204
205compiler.plugin('done', function(stats) {
206 var rawMessages = stats.toJson({}, true);
207 var messages = formatWebpackMessages(rawMessages);
208 if (!messages.errors.length && !messages.warnings.length) {
209 console.log('Compiled successfully!');
210 }
211 if (messages.errors.length) {
212 console.log('Failed to compile.');
213 messages.errors.forEach(e => console.log(e));
214 return;
215 }
216 if (messages.warnings.length) {
217 console.log('Compiled with warnings.');
218 messages.warnings.forEach(w => console.log(w));
219 }
220});
221```
222
223#### `printBuildError(error: Object): void`
224
225Prettify some known build errors.
226Pass an Error object to log a prettified error message in the console.
227
228```
229 const printBuildError = require('react-dev-utils/printBuildError')
230 try {
231 build()
232 } catch(e) {
233 printBuildError(e) // logs prettified message
234 }
235```
236
237#### `getProcessForPort(port: number): string`
238
239Finds the currently running process on `port`.
240Returns a string containing the name and directory, e.g.,
241
242```
243create-react-app
244in /Users/developer/create-react-app
245```
246
247```js
248var getProcessForPort = require('react-dev-utils/getProcessForPort');
249
250getProcessForPort(3000);
251```
252
253#### `launchEditor(fileName: string, lineNumber: number): void`
254
255On 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.
256
257#### `noopServiceWorkerMiddleware(): ExpressMiddleware`
258
259Returns Express middleware that serves a `/service-worker.js` that resets any previously set service worker configuration. Useful for development.
260
261#### `openBrowser(url: string): boolean`
262
263Attempts to open the browser with a given URL.<br>
264On Mac OS X, attempts to reuse an existing Chrome tab via AppleScript.<br>
265Otherwise, falls back to [opn](https://github.com/sindresorhus/opn) behavior.
266
267
268```js
269var path = require('path');
270var openBrowser = require('react-dev-utils/openBrowser');
271
272if (openBrowser('http://localhost:3000')) {
273 console.log('The browser tab has been opened!');
274}
275```
276
277#### `printHostingInstructions(appPackage: Object, publicUrl: string, publicPath: string, buildFolder: string, useYarn: boolean): void`
278
279Prints hosting instructions after the project is built.
280
281Pass 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.
282
283```js
284const appPackage = require(paths.appPackageJson);
285const publicUrl = paths.publicUrl;
286const publicPath = config.output.publicPath;
287printHostingInstructions(appPackage, publicUrl, publicPath, 'build', true);
288```
289
290#### `WebpackDevServerUtils`
291
292##### `choosePort(host: string, defaultPort: number): Promise<number | null>`
293
294Returns 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`.
295
296##### `createCompiler(webpack: Function, config: Object, appName: string, urls: Object, useYarn: boolean): WebpackCompiler`
297
298Creates a Webpack compiler instance for WebpackDevServer with built-in helpful messages. Takes the `require('webpack')` entry point as the first argument. To provide the `urls` argument, use `prepareUrls()` described below.
299
300##### `prepareProxy(proxySetting: string, appPublicFolder: string): Object`
301
302Creates a WebpackDevServer `proxy` configuration object from the `proxy` setting in `package.json`.
303
304##### `prepareUrls(protocol: string, host: string, port: number): Object`
305
306Returns an object with local and remote URLs for the development server. Pass this object to `createCompiler()` described above.
307
308#### `webpackHotDevClient`
309
310This is an alternative client for [WebpackDevServer](https://github.com/webpack/webpack-dev-server) that shows a syntax error overlay.
311
312It currently supports only Webpack 3.x.
313
314```js
315// Webpack development config
316module.exports = {
317 // ...
318 entry: [
319 // You can replace the line below with these two lines if you prefer the
320 // stock client:
321 // require.resolve('webpack-dev-server/client') + '?/',
322 // require.resolve('webpack/hot/dev-server'),
323 'react-dev-utils/webpackHotDevClient',
324 'src/index'
325 ],
326 // ...
327}
328```