-
-
Notifications
You must be signed in to change notification settings - Fork 26.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Extract some utilities into a separate package (#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
- Loading branch information
Showing
21 changed files
with
452 additions
and
192 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
).then(shouldEat => { | ||
if (shouldEat) { | ||
console.log('You have successfully consumed all the candy.'); | ||
} else { | ||
console.log('Phew, candy is still available!'); | ||
} | ||
}); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Oops, something went wrong.