Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract some utilities into a separate package #723

Merged
merged 3 commits into from
Sep 23, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
Expand All @@ -7,7 +6,6 @@
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
// @remove-on-eject-end

// This Webpack plugin lets us interpolate custom variables into `index.html`.
// Usage: `new InterpolateHtmlPlugin({ 'MY_VARIABLE': 42 })`
Expand Down
180 changes: 180 additions & 0 deletions packages/react-dev-utils/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
# react-dev-utils

This package includes some utilities used by [Create React App](https://github.com/facebookincubator/create-react-app).
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})`

This Webpack plugin lets us interpolate custom variables into `index.html`.
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).

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

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

This Webpack plugin ensures `npm install <library>` forces a project rebuild.
We’re not sure why this isn't Webpack's default behavior.
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`

Makes sure that all passed files exist.
Filenames are expected to be absolute.
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!');
```

#### `formatWebpackMessages(stats: WebpackStats): {errors: Array<string>, warnings: Array<string>}`

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');

var compiler = webpack(config);

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

compiler.plugin('done', function(stats) {
var messages = formatWebpackMessages(stats);
if (!messages.errors.length && !messages.warnings.length) {
console.log('Compiled successfully!');
}
if (messages.errors.length) {
console.log('Failed to compile.');
messages.errors.forEach(console.log);
return;
}
if (messages.warnings.length) {
console.log('Compiled with warnings.');
messages.warnings.forEach(console.log);
}
});
```

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

Attempts to open the browser with a given URL.
On Mac OS X, attempts to reuse an existing Chrome tab via AppleScript.
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!');
}
```

#### `prompt`

This function displays a console prompt to the user.

By convention, "no" should be the conservative choice.
If you mistype the answer, we'll always take it as a "no".
You can control the behavior on `<Enter>` with `isYesDefault`.

```js
var prompt = require('react-dev-utils/prompt');
prompt(
'Are you sure you want to eat all the candy?',
false
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I always put a comment for boolean variables with what they mean, otherwise it's pretty confusing :)

/* isYesDefault*/ false

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even better:

prompt('Are you sure you want to eat all the candy?', { default: false });

).then(shouldEat => {
if (shouldEat) {
console.log('You have successfully consumed all the candy.');
} else {
console.log('Phew, candy is still available!');
}
});
```
37 changes: 37 additions & 0 deletions packages/react-dev-utils/WatchMissingNodeModulesPlugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/

// This Webpack plugin ensures `npm install <library>` forces a project rebuild.
// We’re not sure why this isn't Webpack's default behavior.
// See https://github.com/facebookincubator/create-react-app/issues/186.

'use strict';

class WatchMissingNodeModulesPlugin {
constructor(nodeModulesPath) {
this.nodeModulesPath = nodeModulesPath;
}

apply(compiler) {
compiler.plugin('emit', (compilation, callback) => {
var missingDeps = compilation.missingDependencies;
var nodeModulesPath = this.nodeModulesPath;

// If any missing files are expected to appear in node_modules...
if (missingDeps.some(file => file.indexOf(nodeModulesPath) !== -1)) {
// ...tell webpack to watch node_modules recursively until they appear.
compilation.contextDependencies.push(nodeModulesPath);
}

callback();
});
}
}

module.exports = WatchMissingNodeModulesPlugin;
32 changes: 32 additions & 0 deletions packages/react-dev-utils/checkRequiredFiles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/

var fs = require('fs');
var path = require('path');
var chalk = require('chalk');

function checkRequiredFiles(files) {
var currentFilePath;
try {
files.forEach(filePath => {
currentFilePath = filePath;
fs.accessSync(filePath, fs.F_OK);
});
return true;
} catch (err) {
var dirName = path.dirname(currentFilePath);
var fileName = path.basename(currentFilePath);
console.log(chalk.red('Could not find a required file.'));
console.log(chalk.red(' Name: ') + chalk.cyan(fileName));
console.log(chalk.red(' Searched in: ') + chalk.cyan(dirName));
return false;
}
}

module.exports = checkRequiredFiles;
18 changes: 18 additions & 0 deletions packages/react-dev-utils/clearConsole.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/

var isFirstClear = true;
function clearConsole() {
// On first run, clear completely so it doesn't show half screen on Windows.
// On next runs, use a different sequence that properly scrolls back.
process.stdout.write(isFirstClear ? '\x1bc' : '\x1b[2J\x1b[0f');
isFirstClear = false;
}

module.exports = clearConsole;
67 changes: 67 additions & 0 deletions packages/react-dev-utils/formatWebpackMessages.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/

// Some custom utilities to prettify Webpack output.
// This is a little hacky.
// It would be easier if webpack provided a rich error object.
var friendlySyntaxErrorLabel = 'Syntax error:';
function isLikelyASyntaxError(message) {
return message.indexOf(friendlySyntaxErrorLabel) !== -1;
}
function formatMessage(message) {
return message
// Make some common errors shorter:
.replace(
// Babel syntax error
'Module build failed: SyntaxError:',
friendlySyntaxErrorLabel
)
.replace(
// Webpack file not found error
/Module not found: Error: Cannot resolve 'file' or 'directory'/,
'Module not found:'
)
// Internal stacks are generally useless so we strip them
.replace(/^\s*at\s.*:\d+:\d+[\s\)]*\n/gm, '') // at ... ...:x:y
// Webpack loader names obscure CSS filenames
.replace('./~/css-loader!./~/postcss-loader!', '');
}

function formatWebpackMessages(stats) {
var hasErrors = stats.hasErrors();
var hasWarnings = stats.hasWarnings();
if (!hasErrors && !hasWarnings) {
return {
errors: [],
warnings: []
};
}
// We use stats.toJson({}, true) to make output more compact and readable:
// https://github.com/facebookincubator/create-react-app/issues/401#issuecomment-238291901
var json = stats.toJson({}, true);
var formattedErrors = json.errors.map(message =>
'Error in ' + formatMessage(message)
);
var formattedWarnings = json.warnings.map(message =>
'Warning in ' + formatMessage(message)
);
var result = {
errors: formattedErrors,
warnings: formattedWarnings
};
if (result.errors.some(isLikelyASyntaxError)) {
// If there are any syntax errors, show just them.
// This prevents a confusing ESLint parsing error
// preceding a much more useful Babel syntax error.
result.errors = result.errors.filter(isLikelyASyntaxError);
}
return result;
}

module.exports = formatWebpackMessages;
38 changes: 38 additions & 0 deletions packages/react-dev-utils/openBrowser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/

var execSync = require('child_process').execSync;
var opn = require('opn');

function openBrowser(url) {
if (process.platform === 'darwin') {
try {
// Try our best to reuse existing tab
// on OS X Google Chrome with AppleScript
execSync('ps cax | grep "Google Chrome"');
execSync(
'osascript chrome.applescript ' + url,
{cwd: __dirname, stdio: 'ignore'}
);
return true;
} catch (err) {
// Ignore errors.
}
}
// Fallback to opn
// (It will always open new tab)
try {
opn(url);
return true;
} catch (err) {
return false;
}
}

module.exports = openBrowser;
Loading