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

3
This package includes some utilities used by [Create React App](https://github.com/facebookincubator/create-react-app).<br>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Please refer to its documentation:

* [Getting Started](https://github.com/facebookincubator/create-react-app/blob/master/README.md#getting-started) – How to create a new app.
* [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.

## Usage in Create React App Projects

These 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.**

## Usage Outside of Create React App

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

### Entry Points

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

#### `new InterpolateHtmlPlugin(replacements: {[key:string]: string})`

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

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

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

module.exports = {
  output: {
    // ...
    publicPath: publicUrl + '/' 
  },
  // ...
  plugins: [
    // Makes the public URL available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    new InterpolateHtmlPlugin({
      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.
    }),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: path.resolve('public/index.html'),
    }),
    // ...
  ],
  // ...
}
```

Joe Haddad's avatar
Joe Haddad committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

#### `new ModuleScopePlugin(appSrc: string)`

This Webpack plugin ensures that relative imports from app's source directory don't reach outside of it.

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


module.exports = {
  // ...
  plugins: [
    new ModuleScopePlugin(paths.appSrc),
    // ...
  ],
  // ...
}
```

79
80
#### `new WatchMissingNodeModulesPlugin(nodeModulesPath: string)`

81
82
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>
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
See [#186](https://github.com/facebookincubator/create-react-app/issues/186) for details.

```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.
    // See https://github.com/facebookincubator/create-react-app/issues/186
    new WatchMissingNodeModulesPlugin(path.resolve('node_modules'))
  ],
  // ...
}
```

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

106
107
Makes sure that all passed files exist.<br>
Filenames are expected to be absolute.<br>
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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');

if (!checkRequiredFiles([
  path.resolve('public/index.html'),
  path.resolve('src/index.js')
])) {
  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!');
```

133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#### `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.

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

// In your webpack config:
// ...
module: {
   rules: [
     {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        enforce: 'pre',
        use: [
          {
            loader: 'eslint-loader',
            options: {
              // Pass the formatter:
              formatter: eslintFormatter,
            },
          },
        ],
      }
   ]
}
```

163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
#### `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.

##### `printFileSizesAfterBuild(webpackStats: WebpackStats, previousFileSizes: OpaqueFileSizes)`

Prints the JS and CSS asset sizes after the build, and includes a size comparison with `previousFileSizes` that were captured earlier using `measureFileSizesBeforeBuild()`.

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

measureFileSizesBeforeBuild(buildFolder).then(previousFileSizes => {
  return cleanAndRebuild().then(webpackStats => {
    printFileSizesAfterBuild(webpackStats, previousFileSizes);
  });
});
```

186
#### `formatWebpackMessages({errors: Array<string>, warnings: Array<string>}): {errors: Array<string>, warnings: Array<string>}`
187
188
189
190
191
192

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');
193
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
194
195
196
197
198
199
200
201

var compiler = webpack(config);

compiler.plugin('invalid', function() {
  console.log('Compiling...');
});

compiler.plugin('done', function(stats) {
202
203
  var rawMessages = stats.toJson({}, true);
  var messages = formatWebpackMessages(rawMessages);
204
205
206
207
208
  if (!messages.errors.length && !messages.warnings.length) {
    console.log('Compiled successfully!');
  }
  if (messages.errors.length) {
    console.log('Failed to compile.');
209
    messages.errors.forEach(e => console.log(e));
210
211
212
213
    return;
  }
  if (messages.warnings.length) {
    console.log('Compiled with warnings.');
214
    messages.warnings.forEach(w => console.log(w));
215
216
217
218
  }
});
```

219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#### `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);
```

235
236
#### `openBrowser(url: string): boolean`

237
238
Attempts to open the browser with a given URL.<br>
On Mac OS X, attempts to reuse an existing Chrome tab via AppleScript.<br>
239
240
241
242
243
244
245
246
247
248
249
250
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!');
}
```

251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#### `webpackHotDevClient.js`

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

It currently supports only Webpack 1.x.

```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',
    'src/index'
  ],
  // ...
}
```