README.md 13.5 KB
Newer Older
1
2
# react-dev-utils

3
This package includes some utilities used by [Create React App](https://github.com/facebook/create-react-app).<br>
4
5
Please refer to its documentation:

6
7
- [Getting Started](https://github.com/facebook/create-react-app/blob/master/README.md#getting-started) – How to create a new app.
- [User Guide](https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md) – How to develop apps bootstrapped with Create React App.
8
9
10

## Usage in Create React App Projects

11
These utilities come by default with [Create React App](https://github.com/facebook/create-react-app), which includes it by default. **You don’t need to install it separately in Create React App projects.**
12
13
14

## Usage Outside of Create React App

15
If you don’t use Create React App, or if you [ejected](https://github.com/facebook/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
18
19
20

### Entry Points

There is no single entry point. You can only import individual top-level modules.

21
#### `new InterpolateHtmlPlugin(htmlWebpackPlugin: HtmlWebpackPlugin, replacements: {[key:string]: string})`
22

23
This Webpack plugin lets us interpolate custom variables into `index.html`.<br>
24
It 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
27

```js
var path = require('path');
28
var HtmlWebpackPlugin = require('html-webpack-plugin');
29
30
31
32
33
34
35
36
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');

// Webpack config
var publicUrl = '/my-custom-url';

module.exports = {
  output: {
    // ...
37
    publicPath: publicUrl + '/',
38
39
40
  },
  // ...
  plugins: [
41
42
43
44
45
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: path.resolve('public/index.html'),
    }),
46
47
    // Makes the public URL available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
48
49
    new InterpolateHtmlPlugin(HtmlWebpackPlugin, {
      PUBLIC_URL: publicUrl,
50
51
52
53
54
55
      // You can pass any key-value pairs, this was just an example.
      // WHATEVER: 42 will replace %WHATEVER% with 42 in index.html.
    }),
    // ...
  ],
  // ...
56
};
57
58
```

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#### `new InlineChunkHtmlPlugin(htmlWebpackPlugin: HtmlWebpackPlugin, tests: Regex[])`

This Webpack plugin inlines script chunks into `index.html`.<br>
It works in tandem with [HtmlWebpackPlugin](https://github.com/ampedandwired/html-webpack-plugin) 4.x.

```js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');

// Webpack config
var publicUrl = '/my-custom-url';

module.exports = {
  output: {
    // ...
    publicPath: publicUrl + '/',
  },
  // ...
  plugins: [
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: path.resolve('public/index.html'),
    }),
    // Inlines chunks with `runtime` in the name
    new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime/]),
    // ...
  ],
  // ...
};
```

92
#### `new ModuleScopePlugin(appSrc: string | string[], allowedFiles?: string[])`
Joe Haddad's avatar
Joe Haddad committed
93

94
This Webpack plugin ensures that relative imports from app's source directories don't reach outside of it.
Joe Haddad's avatar
Joe Haddad committed
95
96
97
98
99
100
101

```js
var path = require('path');
var ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');

module.exports = {
  // ...
Joe Haddad's avatar
Joe Haddad committed
102
  resolve: {
Joe Haddad's avatar
Joe Haddad committed
103
    // ...
Joe Haddad's avatar
Joe Haddad committed
104
    plugins: [
105
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
Joe Haddad's avatar
Joe Haddad committed
106
107
108
109
      // ...
    ],
    // ...
  },
Joe Haddad's avatar
Joe Haddad committed
110
  // ...
111
};
Joe Haddad's avatar
Joe Haddad committed
112
113
```

114
115
#### `new WatchMissingNodeModulesPlugin(nodeModulesPath: string)`

116
117
This Webpack plugin ensures `npm install <library>` forces a project rebuild.<br>
We’re not sure why this isn't Webpack's default behavior.<br>
118
See [#186](https://github.com/facebook/create-react-app/issues/186) for details.
119
120
121
122
123
124
125
126
127
128
129
130
131

```js
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.
132
    // See https://github.com/facebook/create-react-app/issues/186
133
    new WatchMissingNodeModulesPlugin(path.resolve('node_modules')),
134
135
  ],
  // ...
136
};
137
138
139
140
```

#### `checkRequiredFiles(files: Array<string>): boolean`

141
142
Makes sure that all passed files exist.<br>
Filenames are expected to be absolute.<br>
143
144
145
146
147
148
If a file is not found, prints a warning message and returns `false`.

```js
var path = require('path');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');

149
150
151
152
153
154
if (
  !checkRequiredFiles([
    path.resolve('public/index.html'),
    path.resolve('src/index.js'),
  ])
) {
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
  process.exit(1);
}
```

#### `clearConsole(): void`

Clears the console, hopefully in a cross-platform way.

```js
var clearConsole = require('react-dev-utils/clearConsole');

clearConsole();
console.log('Just cleared the screen!');
```

170
171
#### `eslintFormatter(results: Object): string`

Joe Haddad's avatar
Joe Haddad committed
172
This is our custom ESLint formatter that integrates well with Create React App console output.<br>
173
174
175
176
177
178
179
180
You can use the default one instead if you prefer so.

```js
const eslintFormatter = require('react-dev-utils/eslintFormatter');

// In your webpack config:
// ...
module: {
181
182
183
184
185
186
187
188
189
190
191
  rules: [
    {
      test: /\.(js|jsx)$/,
      include: paths.appSrc,
      enforce: 'pre',
      use: [
        {
          loader: 'eslint-loader',
          options: {
            // Pass the formatter:
            formatter: eslintFormatter,
192
          },
193
194
195
196
        },
      ],
    },
  ];
197
198
199
}
```

200
201
202
203
204
205
#### `FileSizeReporter`

##### `measureFileSizesBeforeBuild(buildFolder: string): Promise<OpaqueFileSizes>`

Captures JS and CSS asset sizes inside the passed `buildFolder`. Save the result value to compare it after the build.

206
##### `printFileSizesAfterBuild(webpackStats: WebpackStats, previousFileSizes: OpaqueFileSizes, buildFolder: string, maxBundleGzipSize?: number, maxChunkGzipSize?: number)`
207

208
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).
209
210
211
212
213
214
215
216
217

```js
var {
  measureFileSizesBeforeBuild,
  printFileSizesAfterBuild,
} = require('react-dev-utils/FileSizeReporter');

measureFileSizesBeforeBuild(buildFolder).then(previousFileSizes => {
  return cleanAndRebuild().then(webpackStats => {
218
    printFileSizesAfterBuild(webpackStats, previousFileSizes, buildFolder);
219
220
221
222
  });
});
```

223
#### `formatWebpackMessages({errors: Array<string>, warnings: Array<string>}): {errors: Array<string>, warnings: Array<string>}`
224
225
226
227
228
229

Extracts and prettifies warning and error messages from webpack [stats](https://github.com/webpack/docs/wiki/node.js-api#stats) object.

```js
var webpack = require('webpack');
var config = require('../config/webpack.config.dev');
230
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
231
232
233

var compiler = webpack(config);

234
compiler.hooks.invalid.tap('invalid', function() {
235
236
237
  console.log('Compiling...');
});

238
compiler.hooks.done.tap('done', function(stats) {
239
240
  var rawMessages = stats.toJson({}, true);
  var messages = formatWebpackMessages(rawMessages);
241
242
243
244
245
  if (!messages.errors.length && !messages.warnings.length) {
    console.log('Compiled successfully!');
  }
  if (messages.errors.length) {
    console.log('Failed to compile.');
246
    messages.errors.forEach(e => console.log(e));
247
248
249
250
    return;
  }
  if (messages.warnings.length) {
    console.log('Compiled with warnings.');
251
    messages.warnings.forEach(w => console.log(w));
252
253
254
255
  }
});
```

256
257
258
259
260
261
262
263
264
265
266
267
268
269
#### `printBuildError(error: Object): void`

Prettify some known build errors.
Pass an Error object to log a prettified error message in the console.

```
  const printBuildError = require('react-dev-utils/printBuildError')
  try {
    build()
  } catch(e) {
    printBuildError(e) // logs prettified message
  }
```

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#### `getProcessForPort(port: number): string`

Finds the currently running process on `port`.
Returns a string containing the name and directory, e.g.,

```
create-react-app
in /Users/developer/create-react-app
```

```js
var getProcessForPort = require('react-dev-utils/getProcessForPort');

getProcessForPort(3000);
```

286
287
288
289
#### `launchEditor(fileName: string, lineNumber: number): void`

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.

290
291
292
293
#### `noopServiceWorkerMiddleware(): ExpressMiddleware`

Returns Express middleware that serves a `/service-worker.js` that resets any previously set service worker configuration. Useful for development.

294
295
#### `openBrowser(url: string): boolean`

296
297
Attempts to open the browser with a given URL.<br>
On Mac OS X, attempts to reuse an existing Chrome tab via AppleScript.<br>
298
299
300
301
302
303
304
305
306
307
308
Otherwise, falls back to [opn](https://github.com/sindresorhus/opn) behavior.

```js
var path = require('path');
var openBrowser = require('react-dev-utils/openBrowser');

if (openBrowser('http://localhost:3000')) {
  console.log('The browser tab has been opened!');
}
```

309
310
311
312
313
314
315
316
317
318
319
320
321
#### `printHostingInstructions(appPackage: Object, publicUrl: string, publicPath: string, buildFolder: string, useYarn: boolean): void`

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.

```js
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrl;
const publicPath = config.output.publicPath;
printHostingInstructions(appPackage, publicUrl, publicPath, 'build', true);
```

322
323
324
325
326
327
328
329
330
331
#### `WebpackDevServerUtils`

##### `choosePort(host: string, defaultPort: number): Promise<number | null>`

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(webpack: Function, config: Object, appName: string, urls: Object, useYarn: boolean): WebpackCompiler`

Creates 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.

332
##### `prepareProxy(proxySetting: string, appPublicFolder: string): Object`
333
334
335
336
337
338
339
340

Creates a WebpackDevServer `proxy` configuration object from the `proxy` setting in `package.json`.

##### `prepareUrls(protocol: string, host: string, port: number): Object`

Returns an object with local and remote URLs for the development server. Pass this object to `createCompiler()` described above.

#### `webpackHotDevClient`
341
342
343

This is an alternative client for [WebpackDevServer](https://github.com/webpack/webpack-dev-server) that shows a syntax error overlay.

344
It currently supports only Webpack 3.x.
345
346
347
348
349
350
351
352
353
354
355

```js
// 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',
356
    'src/index',
357
358
  ],
  // ...
359
};
360
```
361
362
363
364
365
366
367
368
369
370
371
372
373
374

#### `getCSSModuleLocalIdent(context: Object, localIdentName: String, localName: String, options: Object): string`

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]`

```js
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');

// In your webpack config:
// ...
module: {
375
  rules: [
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
    {
      test: /\.module\.css$/,
      use: [
        require.resolve('style-loader'),
        {
          loader: require.resolve('css-loader'),
          options: {
            importLoaders: 1,
            modules: true,
            getLocalIdent: getCSSModuleLocalIdent,
          },
        },
        {
          loader: require.resolve('postcss-loader'),
          options: postCSSLoaderOptions,
        },
      ],
393
394
    },
  ];
395
396
}
```
397
398
399
400
401
402
403
404
405
406

#### `getCacheIdentifier(environment: string, packages: string[]): string`

Returns a cache identifier (string) consisting of the specified environment and related package versions, e.g.,

```js
var getCacheIdentifier = require('react-dev-utils/getCacheIdentifier');

getCacheIdentifier('prod', ['react-dev-utils', 'chalk']); // # => 'prod:react-dev-utils@5.0.0:chalk@2.4.1'
```