source: frontend/node_modules/react-dev-utils/README.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 13.3 KB
Line 
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#### `checkRequiredFiles(files: Array<string>): boolean`
115
116Makes sure that all passed files exist.<br>
117Filenames are expected to be absolute.<br>
118If a file is not found, prints a warning message and returns `false`.
119
120```js
121var path = require('path');
122var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
123
124if (
125 !checkRequiredFiles([
126 path.resolve('public/index.html'),
127 path.resolve('src/index.js'),
128 ])
129) {
130 process.exit(1);
131}
132```
133
134#### `clearConsole(): void`
135
136Clears the console, hopefully in a cross-platform way.
137
138```js
139var clearConsole = require('react-dev-utils/clearConsole');
140
141clearConsole();
142console.log('Just cleared the screen!');
143```
144
145#### `eslintFormatter(results: Object): string`
146
147This is our custom ESLint formatter that integrates well with Create React App console output.<br>
148You can use the default one instead if you prefer so.
149
150```js
151const eslintFormatter = require('react-dev-utils/eslintFormatter');
152
153// In your webpack config:
154// ...
155module: {
156 rules: [
157 {
158 test: /\.(js|jsx)$/,
159 include: paths.appSrc,
160 enforce: 'pre',
161 use: [
162 {
163 loader: 'eslint-loader',
164 options: {
165 // Pass the formatter:
166 formatter: eslintFormatter,
167 },
168 },
169 ],
170 },
171 ];
172}
173```
174
175#### `FileSizeReporter`
176
177##### `measureFileSizesBeforeBuild(buildFolder: string): Promise<OpaqueFileSizes>`
178
179Captures JS and CSS asset sizes inside the passed `buildFolder`. Save the result value to compare it after the build.
180
181##### `printFileSizesAfterBuild(webpackStats: WebpackStats, previousFileSizes: OpaqueFileSizes, buildFolder: string, maxBundleGzipSize?: number, maxChunkGzipSize?: number)`
182
183Prints 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).
184
185```js
186var {
187 measureFileSizesBeforeBuild,
188 printFileSizesAfterBuild,
189} = require('react-dev-utils/FileSizeReporter');
190
191measureFileSizesBeforeBuild(buildFolder).then(previousFileSizes => {
192 return cleanAndRebuild().then(webpackStats => {
193 printFileSizesAfterBuild(webpackStats, previousFileSizes, buildFolder);
194 });
195});
196```
197
198#### `formatWebpackMessages({errors: Array<string>, warnings: Array<string>}): {errors: Array<string>, warnings: Array<string>}`
199
200Extracts and prettifies warning and error messages from webpack [stats](https://github.com/webpack/docs/wiki/node.js-api#stats) object.
201
202```js
203var webpack = require('webpack');
204var config = require('../config/webpack.config.dev');
205var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
206
207var compiler = webpack(config);
208
209compiler.hooks.invalid.tap('invalid', function () {
210 console.log('Compiling...');
211});
212
213compiler.hooks.done.tap('done', function (stats) {
214 var rawMessages = stats.toJson({}, true);
215 var messages = formatWebpackMessages(rawMessages);
216 if (!messages.errors.length && !messages.warnings.length) {
217 console.log('Compiled successfully!');
218 }
219 if (messages.errors.length) {
220 console.log('Failed to compile.');
221 messages.errors.forEach(e => console.log(e));
222 return;
223 }
224 if (messages.warnings.length) {
225 console.log('Compiled with warnings.');
226 messages.warnings.forEach(w => console.log(w));
227 }
228});
229```
230
231#### `printBuildError(error: Object): void`
232
233Prettify some known build errors.
234Pass an Error object to log a prettified error message in the console.
235
236```
237 const printBuildError = require('react-dev-utils/printBuildError')
238 try {
239 build()
240 } catch(e) {
241 printBuildError(e) // logs prettified message
242 }
243```
244
245#### `getProcessForPort(port: number): string`
246
247Finds the currently running process on `port`.
248Returns a string containing the name and directory, e.g.,
249
250```
251create-react-app
252in /Users/developer/create-react-app
253```
254
255```js
256var getProcessForPort = require('react-dev-utils/getProcessForPort');
257
258getProcessForPort(3000);
259```
260
261#### `launchEditor(fileName: string, lineNumber: number): void`
262
263On 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.
264
265#### `noopServiceWorkerMiddleware(servedPath: string): ExpressMiddleware`
266
267Returns Express middleware that serves a `${servedPath}/service-worker.js` that resets any previously set service worker configuration. Useful for development.
268
269#### `redirectServedPathMiddleware(servedPath: string): ExpressMiddleware`
270
271Returns Express middleware that redirects to `${servedPath}/${req.path}`, if `req.url`
272does not start with `servedPath`. Useful for development.
273
274#### `openBrowser(url: string): boolean`
275
276Attempts to open the browser with a given URL.<br>
277On Mac OS X, attempts to reuse an existing Chrome tab via AppleScript.<br>
278Otherwise, falls back to [opn](https://github.com/sindresorhus/opn) behavior.
279
280```js
281var path = require('path');
282var openBrowser = require('react-dev-utils/openBrowser');
283
284if (openBrowser('http://localhost:3000')) {
285 console.log('The browser tab has been opened!');
286}
287```
288
289#### `printHostingInstructions(appPackage: Object, publicUrl: string, publicPath: string, buildFolder: string, useYarn: boolean): void`
290
291Prints hosting instructions after the project is built.
292
293Pass 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.
294
295```js
296const appPackage = require(paths.appPackageJson);
297const publicUrl = paths.publicUrlOrPath;
298const publicPath = config.output.publicPath;
299printHostingInstructions(appPackage, publicUrl, publicPath, 'build', true);
300```
301
302#### `WebpackDevServerUtils`
303
304##### `choosePort(host: string, defaultPort: number): Promise<number | null>`
305
306Returns 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`.
307
308##### `createCompiler(args: Object): WebpackCompiler`
309
310Creates a webpack compiler instance for WebpackDevServer with built-in helpful messages.
311
312The `args` object accepts a number of properties:
313
314- **appName** `string`: The name that will be printed to the terminal.
315- **config** `Object`: The webpack configuration options to be provided to the webpack constructor.
316- **urls** `Object`: To provide the `urls` argument, use `prepareUrls()` described below.
317- **useYarn** `boolean`: If `true`, yarn instructions will be emitted in the terminal instead of npm.
318- **useTypeScript** `boolean`: If `true`, TypeScript type checking will be enabled. Be sure to provide the `devSocket` argument above if this is set to `true`.
319- **webpack** `function`: A reference to the webpack constructor.
320
321##### `prepareProxy(proxySetting: string, appPublicFolder: string, servedPathname: string): Object`
322
323Creates a WebpackDevServer `proxy` configuration object from the `proxy` setting in `package.json`.
324
325##### `prepareUrls(protocol: string, host: string, port: number, pathname: string = '/'): Object`
326
327Returns an object with local and remote URLs for the development server. Pass this object to `createCompiler()` described above.
328
329#### `webpackHotDevClient`
330
331This is an alternative client for [WebpackDevServer](https://github.com/webpack/webpack-dev-server) that shows a syntax error overlay.
332
333It currently supports only webpack 3.x.
334
335```js
336// webpack development config
337module.exports = {
338 // ...
339 entry: [
340 // You can replace the line below with these two lines if you prefer the
341 // stock client:
342 // require.resolve('webpack-dev-server/client') + '?/',
343 // require.resolve('webpack/hot/dev-server'),
344 'react-dev-utils/webpackHotDevClient',
345 'src/index',
346 ],
347 // ...
348};
349```
350
351#### `getCSSModuleLocalIdent(context: Object, localIdentName: String, localName: String, options: Object): string`
352
353Creates a class name for CSS Modules that uses either the filename or folder name if named `index.module.css`.
354
355For `MyFolder/MyComponent.module.css` and class `MyClass` the output will be `MyComponent.module_MyClass__[hash]`
356For `MyFolder/index.module.css` and class `MyClass` the output will be `MyFolder_MyClass__[hash]`
357
358```js
359const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
360
361// In your webpack config:
362// ...
363module: {
364 rules: [
365 {
366 test: /\.module\.css$/,
367 use: [
368 require.resolve('style-loader'),
369 {
370 loader: require.resolve('css-loader'),
371 options: {
372 importLoaders: 1,
373 modules: {
374 getLocalIdent: getCSSModuleLocalIdent,
375 },
376 },
377 },
378 {
379 loader: require.resolve('postcss-loader'),
380 options: postCSSLoaderOptions,
381 },
382 ],
383 },
384 ];
385}
386```
387
388#### `getCacheIdentifier(environment: string, packages: string[]): string`
389
390Returns a cache identifier (string) consisting of the specified environment and related package versions, e.g.,
391
392```js
393var getCacheIdentifier = require('react-dev-utils/getCacheIdentifier');
394
395getCacheIdentifier('prod', ['react-dev-utils', 'chalk']); // # => 'prod:react-dev-utils@5.0.0:chalk@3.0.0'
396```
Note: See TracBrowser for help on using the repository browser.