UNPKG

15.1 kBMarkdownView Raw
1# react-dev-utils
2
3This package includes some utilities used by [Create React App](https://github.com/facebook/create-react-app).<br>
4Please refer to its documentation:
5
6- [Getting Started](https://facebook.github.io/create-react-app/docs/getting-started) – How to create a new app.
7- [User Guide](https://facebook.github.io/create-react-app/) – 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/facebook/create-react-app). **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://facebook.github.io/create-react-app/docs/available-scripts#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(htmlWebpackPlugin: HtmlWebpackPlugin, 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-webpack-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 // Generates an `index.html` file with the <script> injected.
42 new HtmlWebpackPlugin({
43 inject: true,
44 template: path.resolve('public/index.html'),
45 }),
46 // Makes the public URL available as %PUBLIC_URL% in index.html, e.g.:
47 // <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
48 new InterpolateHtmlPlugin(HtmlWebpackPlugin, {
49 PUBLIC_URL: publicUrl,
50 // You can pass any key-value pairs, this was just an example.
51 // WHATEVER: 42 will replace %WHATEVER% with 42 in index.html.
52 }),
53 // ...
54 ],
55 // ...
56};
57```
58
59#### `new InlineChunkHtmlPlugin(htmlWebpackPlugin: HtmlWebpackPlugin, tests: Regex[])`
60
61This webpack plugin inlines script chunks into `index.html`.<br>
62It works in tandem with [HtmlWebpackPlugin](https://github.com/ampedandwired/html-webpack-plugin) 4.x.
63
64```js
65var path = require('path');
66var HtmlWebpackPlugin = require('html-webpack-plugin');
67var InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
68
69// webpack config
70var publicUrl = '/my-custom-url';
71
72module.exports = {
73 output: {
74 // ...
75 publicPath: publicUrl + '/',
76 },
77 // ...
78 plugins: [
79 // Generates an `index.html` file with the <script> injected.
80 new HtmlWebpackPlugin({
81 inject: true,
82 template: path.resolve('public/index.html'),
83 }),
84 // Inlines chunks with `runtime` in the name
85 new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime/]),
86 // ...
87 ],
88 // ...
89};
90```
91
92#### `new ModuleScopePlugin(appSrc: string | string[], allowedFiles?: string[])`
93
94This webpack plugin ensures that relative imports from app's source directories don't reach outside of it.
95
96```js
97var path = require('path');
98var ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
99
100module.exports = {
101 // ...
102 resolve: {
103 // ...
104 plugins: [
105 new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
106 // ...
107 ],
108 // ...
109 },
110 // ...
111};
112```
113
114#### `new WatchMissingNodeModulesPlugin(nodeModulesPath: string)`
115
116This webpack plugin ensures `npm install <library>` forces a project rebuild.<br>
117We’re not sure why this isn't webpack's default behavior.<br>
118See [#186](https://github.com/facebook/create-react-app/issues/186) for details.
119
120```js
121var path = require('path');
122var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
123
124// webpack config
125module.exports = {
126 // ...
127 plugins: [
128 // ...
129 // If you require a missing module and then `npm install` it, you still have
130 // to restart the development server for webpack to discover it. This plugin
131 // 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#### `checkRequiredFiles(files: Array<string>): boolean`
140
141Makes sure that all passed files exist.<br>
142Filenames are expected to be absolute.<br>
143If a file is not found, prints a warning message and returns `false`.
144
145```js
146var path = require('path');
147var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
148
149if (
150 !checkRequiredFiles([
151 path.resolve('public/index.html'),
152 path.resolve('src/index.js'),
153 ])
154) {
155 process.exit(1);
156}
157```
158
159#### `clearConsole(): void`
160
161Clears the console, hopefully in a cross-platform way.
162
163```js
164var clearConsole = require('react-dev-utils/clearConsole');
165
166clearConsole();
167console.log('Just cleared the screen!');
168```
169
170#### `eslintFormatter(results: Object): string`
171
172This is our custom ESLint formatter that integrates well with Create React App console output.<br>
173You can use the default one instead if you prefer so.
174
175```js
176const eslintFormatter = require('react-dev-utils/eslintFormatter');
177
178// In your webpack config:
179// ...
180module: {
181 rules: [
182 {
183 test: /\.(js|jsx)$/,
184 include: paths.appSrc,
185 enforce: 'pre',
186 use: [
187 {
188 loader: 'eslint-loader',
189 options: {
190 // Pass the formatter:
191 formatter: eslintFormatter,
192 },
193 },
194 ],
195 },
196 ];
197}
198```
199
200#### `FileSizeReporter`
201
202##### `measureFileSizesBeforeBuild(buildFolder: string): Promise<OpaqueFileSizes>`
203
204Captures JS and CSS asset sizes inside the passed `buildFolder`. Save the result value to compare it after the build.
205
206##### `printFileSizesAfterBuild(webpackStats: WebpackStats, previousFileSizes: OpaqueFileSizes, buildFolder: string, maxBundleGzipSize?: number, maxChunkGzipSize?: number)`
207
208Prints 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```js
211var {
212 measureFileSizesBeforeBuild,
213 printFileSizesAfterBuild,
214} = require('react-dev-utils/FileSizeReporter');
215
216measureFileSizesBeforeBuild(buildFolder).then(previousFileSizes => {
217 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
225Extracts and prettifies warning and error messages from webpack [stats](https://github.com/webpack/docs/wiki/node.js-api#stats) object.
226
227```js
228var webpack = require('webpack');
229var config = require('../config/webpack.config.dev');
230var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
231
232var compiler = webpack(config);
233
234compiler.hooks.invalid.tap('invalid', function() {
235 console.log('Compiling...');
236});
237
238compiler.hooks.done.tap('done', function(stats) {
239 var rawMessages = stats.toJson({}, true);
240 var messages = formatWebpackMessages(rawMessages);
241 if (!messages.errors.length && !messages.warnings.length) {
242 console.log('Compiled successfully!');
243 }
244 if (messages.errors.length) {
245 console.log('Failed to compile.');
246 messages.errors.forEach(e => console.log(e));
247 return;
248 }
249 if (messages.warnings.length) {
250 console.log('Compiled with warnings.');
251 messages.warnings.forEach(w => console.log(w));
252 }
253});
254```
255
256#### `printBuildError(error: Object): void`
257
258Prettify some known build errors.
259Pass an Error object to log a prettified error message in the console.
260
261```
262 const printBuildError = require('react-dev-utils/printBuildError')
263 try {
264 build()
265 } catch(e) {
266 printBuildError(e) // logs prettified message
267 }
268```
269
270#### `getProcessForPort(port: number): string`
271
272Finds the currently running process on `port`.
273Returns a string containing the name and directory, e.g.,
274
275```
276create-react-app
277in /Users/developer/create-react-app
278```
279
280```js
281var getProcessForPort = require('react-dev-utils/getProcessForPort');
282
283getProcessForPort(3000);
284```
285
286#### `launchEditor(fileName: string, lineNumber: number): void`
287
288On 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.
289
290#### `noopServiceWorkerMiddleware(servedPath: string): ExpressMiddleware`
291
292Returns Express middleware that serves a `${servedPath}/service-worker.js` that resets any previously set service worker configuration. Useful for development.
293
294#### `redirectServedPathMiddleware(servedPath: string): ExpressMiddleware`
295
296Returns Express middleware that redirects to `${servedPath}/${req.path}`, if `req.url`
297does not start with `servedPath`. Useful for development.
298
299#### `openBrowser(url: string): boolean`
300
301Attempts to open the browser with a given URL.<br>
302On Mac OS X, attempts to reuse an existing Chrome tab via AppleScript.<br>
303Otherwise, falls back to [opn](https://github.com/sindresorhus/opn) behavior.
304
305```js
306var path = require('path');
307var openBrowser = require('react-dev-utils/openBrowser');
308
309if (openBrowser('http://localhost:3000')) {
310 console.log('The browser tab has been opened!');
311}
312```
313
314#### `printHostingInstructions(appPackage: Object, publicUrl: string, publicPath: string, buildFolder: string, useYarn: boolean): void`
315
316Prints hosting instructions after the project is built.
317
318Pass your parsed `package.json` object as `appPackage`, your 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.
319
320```js
321const appPackage = require(paths.appPackageJson);
322const publicUrl = paths.publicUrlOrPath;
323const publicPath = config.output.publicPath;
324printHostingInstructions(appPackage, publicUrl, publicPath, 'build', true);
325```
326
327#### `WebpackDevServerUtils`
328
329##### `choosePort(host: string, defaultPort: number): Promise<number | null>`
330
331Returns 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`.
332
333##### `createCompiler(args: Object): WebpackCompiler`
334
335Creates a webpack compiler instance for WebpackDevServer with built-in helpful messages.
336
337The `args` object accepts a number of properties:
338
339- **appName** `string`: The name that will be printed to the terminal.
340- **config** `Object`: The webpack configuration options to be provided to the webpack constructor.
341- **devSocket** `Object`: 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.
342- **urls** `Object`: To provide the `urls` argument, use `prepareUrls()` described below.
343- **useYarn** `boolean`: If `true`, yarn instructions will be emitted in the terminal instead of npm.
344- **useTypeScript** `boolean`: If `true`, TypeScript type checking will be enabled. Be sure to provide the `devSocket` argument above if this is set to `true`.
345- **tscCompileOnError** `boolean`: 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.
346- **webpack** `function`: A reference to the webpack constructor.
347
348##### `prepareProxy(proxySetting: string, appPublicFolder: string, servedPathname: string): Object`
349
350Creates a WebpackDevServer `proxy` configuration object from the `proxy` setting in `package.json`.
351
352##### `prepareUrls(protocol: string, host: string, port: number, pathname: string = '/'): Object`
353
354Returns an object with local and remote URLs for the development server. Pass this object to `createCompiler()` described above.
355
356#### `webpackHotDevClient`
357
358This is an alternative client for [WebpackDevServer](https://github.com/webpack/webpack-dev-server) that shows a syntax error overlay.
359
360It currently supports only webpack 3.x.
361
362```js
363// webpack development config
364module.exports = {
365 // ...
366 entry: [
367 // You can replace the line below with these two lines if you prefer the
368 // stock client:
369 // require.resolve('webpack-dev-server/client') + '?/',
370 // require.resolve('webpack/hot/dev-server'),
371 'react-dev-utils/webpackHotDevClient',
372 'src/index',
373 ],
374 // ...
375};
376```
377
378#### `getCSSModuleLocalIdent(context: Object, localIdentName: String, localName: String, options: Object): string`
379
380Creates a class name for CSS Modules that uses either the filename or folder name if named `index.module.css`.
381
382For `MyFolder/MyComponent.module.css` and class `MyClass` the output will be `MyComponent.module_MyClass__[hash]`
383For `MyFolder/index.module.css` and class `MyClass` the output will be `MyFolder_MyClass__[hash]`
384
385```js
386const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
387
388// In your webpack config:
389// ...
390module: {
391 rules: [
392 {
393 test: /\.module\.css$/,
394 use: [
395 require.resolve('style-loader'),
396 {
397 loader: require.resolve('css-loader'),
398 options: {
399 importLoaders: 1,
400 modules: {
401 getLocalIdent: getCSSModuleLocalIdent,
402 },
403 },
404 },
405 {
406 loader: require.resolve('postcss-loader'),
407 options: postCSSLoaderOptions,
408 },
409 ],
410 },
411 ];
412}
413```
414
415#### `getCacheIdentifier(environment: string, packages: string[]): string`
416
417Returns a cache identifier (string) consisting of the specified environment and related package versions, e.g.,
418
419```js
420var getCacheIdentifier = require('react-dev-utils/getCacheIdentifier');
421
422getCacheIdentifier('prod', ['react-dev-utils', 'chalk']); // # => 'prod:react-dev-utils@5.0.0:chalk@3.0.0'
423```