Skip to content

Commit e5bf5af

Browse files
authored
Extract some utilities into a separate package (facebook#723)
* Extract some utilities into a separate package * Add utils dir to `files` in package.json * Do not create an empty `utils` dir on eject
1 parent c4a936e commit e5bf5af

21 files changed

+452
-192
lines changed

packages/react-scripts/scripts/utils/InterpolateHtmlPlugin.js packages/react-dev-utils/InterpolateHtmlPlugin.js

-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// @remove-on-eject-begin
21
/**
32
* Copyright (c) 2015-present, Facebook, Inc.
43
* All rights reserved.
@@ -7,7 +6,6 @@
76
* LICENSE file in the root directory of this source tree. An additional grant
87
* of patent rights can be found in the PATENTS file in the same directory.
98
*/
10-
// @remove-on-eject-end
119

1210
// This Webpack plugin lets us interpolate custom variables into `index.html`.
1311
// Usage: `new InterpolateHtmlPlugin({ 'MY_VARIABLE': 42 })`

packages/react-dev-utils/README.md

+180
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
# react-dev-utils
2+
3+
This package includes some utilities used by [Create React App](https://github.com/facebookincubator/create-react-app).
4+
Please 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+
11+
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.**
12+
13+
## Usage Outside of Create React App
14+
15+
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.
16+
17+
### Entry Points
18+
19+
There is no single entry point. You can only import individual top-level modules.
20+
21+
#### `new InterpolateHtmlPlugin(replacements: {[key:string]: string})`
22+
23+
This Webpack plugin lets us interpolate custom variables into `index.html`.
24+
It works in tandem with [HtmlWebpackPlugin](https://github.com/ampedandwired/html-dev-plugin) 2.x via its [events](https://github.com/ampedandwired/html-dev-plugin#events).
25+
26+
```js
27+
var path = require('path');
28+
var HtmlWebpackPlugin = require('html-dev-plugin');
29+
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
30+
31+
// Webpack config
32+
var publicUrl = '/my-custom-url';
33+
34+
module.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+
#### `new WatchMissingNodeModulesPlugin(nodeModulesPath: string)`
60+
61+
This Webpack plugin ensures `npm install <library>` forces a project rebuild.
62+
We’re not sure why this isn't Webpack's default behavior.
63+
See [#186](https://github.com/facebookincubator/create-react-app/issues/186) for details.
64+
65+
```js
66+
var path = require('path');
67+
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
68+
69+
// Webpack config
70+
module.exports = {
71+
// ...
72+
plugins: [
73+
// ...
74+
// If you require a missing module and then `npm install` it, you still have
75+
// to restart the development server for Webpack to discover it. This plugin
76+
// makes the discovery automatic so you don't have to restart.
77+
// See https://github.com/facebookincubator/create-react-app/issues/186
78+
new WatchMissingNodeModulesPlugin(path.resolve('node_modules'))
79+
],
80+
// ...
81+
}
82+
```
83+
84+
#### `checkRequiredFiles(files: Array<string>): boolean`
85+
86+
Makes sure that all passed files exist.
87+
Filenames are expected to be absolute.
88+
If a file is not found, prints a warning message and returns `false`.
89+
90+
```js
91+
var path = require('path');
92+
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
93+
94+
if (!checkRequiredFiles([
95+
path.resolve('public/index.html'),
96+
path.resolve('src/index.js')
97+
])) {
98+
process.exit(1);
99+
}
100+
```
101+
102+
#### `clearConsole(): void`
103+
104+
Clears the console, hopefully in a cross-platform way.
105+
106+
```js
107+
var clearConsole = require('react-dev-utils/clearConsole');
108+
109+
clearConsole();
110+
console.log('Just cleared the screen!');
111+
```
112+
113+
#### `formatWebpackMessages(stats: WebpackStats): {errors: Array<string>, warnings: Array<string>}`
114+
115+
Extracts and prettifies warning and error messages from webpack [stats](https://github.com/webpack/docs/wiki/node.js-api#stats) object.
116+
117+
```js
118+
var webpack = require('webpack');
119+
var config = require('../config/webpack.config.dev');
120+
121+
var compiler = webpack(config);
122+
123+
compiler.plugin('invalid', function() {
124+
console.log('Compiling...');
125+
});
126+
127+
compiler.plugin('done', function(stats) {
128+
var messages = formatWebpackMessages(stats);
129+
if (!messages.errors.length && !messages.warnings.length) {
130+
console.log('Compiled successfully!');
131+
}
132+
if (messages.errors.length) {
133+
console.log('Failed to compile.');
134+
messages.errors.forEach(console.log);
135+
return;
136+
}
137+
if (messages.warnings.length) {
138+
console.log('Compiled with warnings.');
139+
messages.warnings.forEach(console.log);
140+
}
141+
});
142+
```
143+
144+
#### `openBrowser(url: string): boolean`
145+
146+
Attempts to open the browser with a given URL.
147+
On Mac OS X, attempts to reuse an existing Chrome tab via AppleScript.
148+
Otherwise, falls back to [opn](https://github.com/sindresorhus/opn) behavior.
149+
150+
151+
```js
152+
var path = require('path');
153+
var openBrowser = require('react-dev-utils/openBrowser');
154+
155+
if (openBrowser('http://localhost:3000')) {
156+
console.log('The browser tab has been opened!');
157+
}
158+
```
159+
160+
#### `prompt`
161+
162+
This function displays a console prompt to the user.
163+
164+
By convention, "no" should be the conservative choice.
165+
If you mistype the answer, we'll always take it as a "no".
166+
You can control the behavior on `<Enter>` with `isYesDefault`.
167+
168+
```js
169+
var prompt = require('react-dev-utils/prompt');
170+
prompt(
171+
'Are you sure you want to eat all the candy?',
172+
false
173+
).then(shouldEat => {
174+
if (shouldEat) {
175+
console.log('You have successfully consumed all the candy.');
176+
} else {
177+
console.log('Phew, candy is still available!');
178+
}
179+
});
180+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Copyright (c) 2015-present, Facebook, Inc.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the BSD-style license found in the
6+
* LICENSE file in the root directory of this source tree. An additional grant
7+
* of patent rights can be found in the PATENTS file in the same directory.
8+
*/
9+
10+
// This Webpack plugin ensures `npm install <library>` forces a project rebuild.
11+
// We’re not sure why this isn't Webpack's default behavior.
12+
// See https://github.com/facebookincubator/create-react-app/issues/186.
13+
14+
'use strict';
15+
16+
class WatchMissingNodeModulesPlugin {
17+
constructor(nodeModulesPath) {
18+
this.nodeModulesPath = nodeModulesPath;
19+
}
20+
21+
apply(compiler) {
22+
compiler.plugin('emit', (compilation, callback) => {
23+
var missingDeps = compilation.missingDependencies;
24+
var nodeModulesPath = this.nodeModulesPath;
25+
26+
// If any missing files are expected to appear in node_modules...
27+
if (missingDeps.some(file => file.indexOf(nodeModulesPath) !== -1)) {
28+
// ...tell webpack to watch node_modules recursively until they appear.
29+
compilation.contextDependencies.push(nodeModulesPath);
30+
}
31+
32+
callback();
33+
});
34+
}
35+
}
36+
37+
module.exports = WatchMissingNodeModulesPlugin;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Copyright (c) 2015-present, Facebook, Inc.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the BSD-style license found in the
6+
* LICENSE file in the root directory of this source tree. An additional grant
7+
* of patent rights can be found in the PATENTS file in the same directory.
8+
*/
9+
10+
var fs = require('fs');
11+
var path = require('path');
12+
var chalk = require('chalk');
13+
14+
function checkRequiredFiles(files) {
15+
var currentFilePath;
16+
try {
17+
files.forEach(filePath => {
18+
currentFilePath = filePath;
19+
fs.accessSync(filePath, fs.F_OK);
20+
});
21+
return true;
22+
} catch (err) {
23+
var dirName = path.dirname(currentFilePath);
24+
var fileName = path.basename(currentFilePath);
25+
console.log(chalk.red('Could not find a required file.'));
26+
console.log(chalk.red(' Name: ') + chalk.cyan(fileName));
27+
console.log(chalk.red(' Searched in: ') + chalk.cyan(dirName));
28+
return false;
29+
}
30+
}
31+
32+
module.exports = checkRequiredFiles;
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* Copyright (c) 2015-present, Facebook, Inc.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the BSD-style license found in the
6+
* LICENSE file in the root directory of this source tree. An additional grant
7+
* of patent rights can be found in the PATENTS file in the same directory.
8+
*/
9+
10+
var isFirstClear = true;
11+
function clearConsole() {
12+
// On first run, clear completely so it doesn't show half screen on Windows.
13+
// On next runs, use a different sequence that properly scrolls back.
14+
process.stdout.write(isFirstClear ? '\x1bc' : '\x1b[2J\x1b[0f');
15+
isFirstClear = false;
16+
}
17+
18+
module.exports = clearConsole;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* Copyright (c) 2015-present, Facebook, Inc.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the BSD-style license found in the
6+
* LICENSE file in the root directory of this source tree. An additional grant
7+
* of patent rights can be found in the PATENTS file in the same directory.
8+
*/
9+
10+
// Some custom utilities to prettify Webpack output.
11+
// This is a little hacky.
12+
// It would be easier if webpack provided a rich error object.
13+
var friendlySyntaxErrorLabel = 'Syntax error:';
14+
function isLikelyASyntaxError(message) {
15+
return message.indexOf(friendlySyntaxErrorLabel) !== -1;
16+
}
17+
function formatMessage(message) {
18+
return message
19+
// Make some common errors shorter:
20+
.replace(
21+
// Babel syntax error
22+
'Module build failed: SyntaxError:',
23+
friendlySyntaxErrorLabel
24+
)
25+
.replace(
26+
// Webpack file not found error
27+
/Module not found: Error: Cannot resolve 'file' or 'directory'/,
28+
'Module not found:'
29+
)
30+
// Internal stacks are generally useless so we strip them
31+
.replace(/^\s*at\s.*:\d+:\d+[\s\)]*\n/gm, '') // at ... ...:x:y
32+
// Webpack loader names obscure CSS filenames
33+
.replace('./~/css-loader!./~/postcss-loader!', '');
34+
}
35+
36+
function formatWebpackMessages(stats) {
37+
var hasErrors = stats.hasErrors();
38+
var hasWarnings = stats.hasWarnings();
39+
if (!hasErrors && !hasWarnings) {
40+
return {
41+
errors: [],
42+
warnings: []
43+
};
44+
}
45+
// We use stats.toJson({}, true) to make output more compact and readable:
46+
// https://github.com/facebookincubator/create-react-app/issues/401#issuecomment-238291901
47+
var json = stats.toJson({}, true);
48+
var formattedErrors = json.errors.map(message =>
49+
'Error in ' + formatMessage(message)
50+
);
51+
var formattedWarnings = json.warnings.map(message =>
52+
'Warning in ' + formatMessage(message)
53+
);
54+
var result = {
55+
errors: formattedErrors,
56+
warnings: formattedWarnings
57+
};
58+
if (result.errors.some(isLikelyASyntaxError)) {
59+
// If there are any syntax errors, show just them.
60+
// This prevents a confusing ESLint parsing error
61+
// preceding a much more useful Babel syntax error.
62+
result.errors = result.errors.filter(isLikelyASyntaxError);
63+
}
64+
return result;
65+
}
66+
67+
module.exports = formatWebpackMessages;
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Copyright (c) 2015-present, Facebook, Inc.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the BSD-style license found in the
6+
* LICENSE file in the root directory of this source tree. An additional grant
7+
* of patent rights can be found in the PATENTS file in the same directory.
8+
*/
9+
10+
var execSync = require('child_process').execSync;
11+
var opn = require('opn');
12+
13+
function openBrowser(url) {
14+
if (process.platform === 'darwin') {
15+
try {
16+
// Try our best to reuse existing tab
17+
// on OS X Google Chrome with AppleScript
18+
execSync('ps cax | grep "Google Chrome"');
19+
execSync(
20+
'osascript chrome.applescript ' + url,
21+
{cwd: __dirname, stdio: 'ignore'}
22+
);
23+
return true;
24+
} catch (err) {
25+
// Ignore errors.
26+
}
27+
}
28+
// Fallback to opn
29+
// (It will always open new tab)
30+
try {
31+
opn(url);
32+
return true;
33+
} catch (err) {
34+
return false;
35+
}
36+
}
37+
38+
module.exports = openBrowser;

0 commit comments

Comments
 (0)