Commit e5bf5af2 authored by Dan Abramov's avatar Dan Abramov Committed by GitHub
Browse files

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
parent c4a936ec
No related merge requests found
Showing with 452 additions and 124 deletions
+452 -124
// @remove-on-eject-begin
/** /**
* Copyright (c) 2015-present, Facebook, Inc. * Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved. * All rights reserved.
...@@ -7,7 +6,6 @@ ...@@ -7,7 +6,6 @@
* LICENSE file in the root directory of this source tree. An additional grant * 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. * 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`. // This Webpack plugin lets us interpolate custom variables into `index.html`.
// Usage: `new InterpolateHtmlPlugin({ 'MY_VARIABLE': 42 })` // Usage: `new InterpolateHtmlPlugin({ 'MY_VARIABLE': 42 })`
......
# 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!');
}
});
```
// @remove-on-eject-begin
/** /**
* Copyright (c) 2015-present, Facebook, Inc. * Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved. * All rights reserved.
...@@ -7,29 +6,32 @@ ...@@ -7,29 +6,32 @@
* LICENSE file in the root directory of this source tree. An additional grant * 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. * of patent rights can be found in the PATENTS file in the same directory.
*/ */
// @remove-on-eject-end
// This Webpack plugin ensures `npm install <library>` forces a project rebuild. // This Webpack plugin ensures `npm install <library>` forces a project rebuild.
// We’re not sure why this isn't Webpack's default behavior. // We’re not sure why this isn't Webpack's default behavior.
// See https://github.com/facebookincubator/create-react-app/issues/186. // See https://github.com/facebookincubator/create-react-app/issues/186.
function WatchMissingNodeModulesPlugin(nodeModulesPath) { 'use strict';
this.nodeModulesPath = nodeModulesPath;
} class WatchMissingNodeModulesPlugin {
constructor(nodeModulesPath) {
this.nodeModulesPath = nodeModulesPath;
}
WatchMissingNodeModulesPlugin.prototype.apply = function (compiler) { apply(compiler) {
compiler.plugin('emit', (compilation, callback) => { compiler.plugin('emit', (compilation, callback) => {
var missingDeps = compilation.missingDependencies; var missingDeps = compilation.missingDependencies;
var nodeModulesPath = this.nodeModulesPath; var nodeModulesPath = this.nodeModulesPath;
// If any missing files are expected to appear in node_modules... // If any missing files are expected to appear in node_modules...
if (missingDeps.some(file => file.indexOf(nodeModulesPath) !== -1)) { if (missingDeps.some(file => file.indexOf(nodeModulesPath) !== -1)) {
// ...tell webpack to watch node_modules recursively until they appear. // ...tell webpack to watch node_modules recursively until they appear.
compilation.contextDependencies.push(nodeModulesPath); compilation.contextDependencies.push(nodeModulesPath);
} }
callback(); callback();
}); });
}
} }
module.exports = WatchMissingNodeModulesPlugin; module.exports = WatchMissingNodeModulesPlugin;
// @remove-on-eject-begin
/** /**
* Copyright (c) 2015-present, Facebook, Inc. * Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved. * All rights reserved.
...@@ -7,27 +6,27 @@ ...@@ -7,27 +6,27 @@
* LICENSE file in the root directory of this source tree. An additional grant * 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. * of patent rights can be found in the PATENTS file in the same directory.
*/ */
// @remove-on-eject-end
const fs = require('fs'); var fs = require('fs');
const path = require('path'); var path = require('path');
const chalk = require('chalk'); var chalk = require('chalk');
const paths = require('../../config/paths');
function checkRequiredFiles() { function checkRequiredFiles(files) {
const filesPathToCheck = [paths.appHtml, paths.appIndexJs]; var currentFilePath;
filesPathToCheck.forEach(filePath => { try {
try { files.forEach(filePath => {
currentFilePath = filePath;
fs.accessSync(filePath, fs.F_OK); fs.accessSync(filePath, fs.F_OK);
} catch (err) { });
const dirName = path.dirname(filePath); return true;
const fileName = path.basename(filePath); } catch (err) {
console.log(chalk.red('Could not find a required file.')); var dirName = path.dirname(currentFilePath);
console.log(chalk.red(' Name: ') + chalk.cyan(fileName)); var fileName = path.basename(currentFilePath);
console.log(chalk.red(' Searched in: ') + chalk.cyan(dirName)); console.log(chalk.red('Could not find a required file.'));
process.exit(1); console.log(chalk.red(' Name: ') + chalk.cyan(fileName));
} console.log(chalk.red(' Searched in: ') + chalk.cyan(dirName));
}); return false;
}
} }
module.exports = checkRequiredFiles; module.exports = checkRequiredFiles;
/**
* 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;
/**
* 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;
/**
* 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;
-- @remove-on-eject-begin
(* (*
Copyright (c) 2015-present, Facebook, Inc. Copyright (c) 2015-present, Facebook, Inc.
All rights reserved. All rights reserved.
...@@ -7,7 +6,6 @@ This source code is licensed under the BSD-style license found in the ...@@ -7,7 +6,6 @@ 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 -- 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. of patent rights can be found in the PATENTS file in the same directory.
*) *)
-- @remove-on-eject-end
on run argv on run argv
set theURL to item 1 of argv set theURL to item 1 of argv
......
{
"name": "react-dev-utils",
"version": "0.1.0",
"description": "Webpack utilities used by Create React App",
"repository": "facebookincubator/create-react-app",
"license": "BSD-3-Clause",
"bugs": {
"url": "https://github.com/facebookincubator/create-react-app/issues"
},
"engines": {
"node": ">=4"
},
"files": [
"clearConsole.js",
"checkRequiredFiles.js",
"formatWebpackMessages.js",
"InterpolateHtmlPlugin.js",
"openChrome.applescript",
"openBrowser.js",
"prompt.js",
"WatchMissingNodeModulesPlugin.js"
],
"dependencies": {
"chalk": "1.1.3",
"opn": "4.0.2"
},
"peerDependencies": {
"webpack": "^1.13.2"
}
}
// @remove-on-eject-begin
/** /**
* Copyright (c) 2015-present, Facebook, Inc. * Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved. * All rights reserved.
...@@ -7,14 +6,13 @@ ...@@ -7,14 +6,13 @@
* LICENSE file in the root directory of this source tree. An additional grant * 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. * of patent rights can be found in the PATENTS file in the same directory.
*/ */
// @remove-on-eject-end
var rl = require('readline'); var rl = require('readline');
// Convention: "no" should be the conservative choice. // Convention: "no" should be the conservative choice.
// If you mistype the answer, we'll always take it as a "no". // If you mistype the answer, we'll always take it as a "no".
// You can control the behavior on <Enter> with `isYesDefault`. // You can control the behavior on <Enter> with `isYesDefault`.
module.exports = function (question, isYesDefault) { function prompt(question, isYesDefault) {
if (typeof isYesDefault !== 'boolean') { if (typeof isYesDefault !== 'boolean') {
throw new Error('Provide explicit boolean isYesDefault as second argument.'); throw new Error('Provide explicit boolean isYesDefault as second argument.');
} }
...@@ -40,3 +38,5 @@ module.exports = function (question, isYesDefault) { ...@@ -40,3 +38,5 @@ module.exports = function (question, isYesDefault) {
}); });
}); });
}; };
module.exports = prompt;
...@@ -15,9 +15,9 @@ var webpack = require('webpack'); ...@@ -15,9 +15,9 @@ var webpack = require('webpack');
var findCacheDir = require('find-cache-dir'); var findCacheDir = require('find-cache-dir');
var HtmlWebpackPlugin = require('html-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin');
var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
var InterpolateHtmlPlugin = require('../scripts/utils/InterpolateHtmlPlugin'); var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var WatchMissingNodeModulesPlugin = require('../scripts/utils/WatchMissingNodeModulesPlugin'); var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
var getClientEnvironment = require('../scripts/utils/getClientEnvironment'); var getClientEnvironment = require('./env');
var paths = require('./paths'); var paths = require('./paths');
// Webpack uses `publicPath` to determine where the app is being served from. // Webpack uses `publicPath` to determine where the app is being served from.
...@@ -204,7 +204,7 @@ module.exports = { ...@@ -204,7 +204,7 @@ module.exports = {
template: paths.appHtml, template: paths.appHtml,
}), }),
// Makes some environment variables available to the JS code, for example: // Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env), new webpack.DefinePlugin(env),
// This is necessary to emit hot updates (currently CSS only): // This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(), new webpack.HotModuleReplacementPlugin(),
......
...@@ -14,10 +14,10 @@ var autoprefixer = require('autoprefixer'); ...@@ -14,10 +14,10 @@ var autoprefixer = require('autoprefixer');
var webpack = require('webpack'); var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var url = require('url'); var url = require('url');
var paths = require('./paths'); var paths = require('./paths');
var InterpolateHtmlPlugin = require('../scripts/utils/InterpolateHtmlPlugin'); var getClientEnvironment = require('./env');
var getClientEnvironment = require('../scripts/utils/getClientEnvironment');
function ensureSlash(path, needsSlash) { function ensureSlash(path, needsSlash) {
var hasSlash = path.endsWith('/'); var hasSlash = path.endsWith('/');
...@@ -227,7 +227,7 @@ module.exports = { ...@@ -227,7 +227,7 @@ module.exports = {
} }
}), }),
// Makes some environment variables available to the JS code, for example: // Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV was set to production here. // It is absolutely essential that NODE_ENV was set to production here.
// Otherwise React will be compiled in the very slow development mode. // Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env), new webpack.DefinePlugin(env),
......
...@@ -16,7 +16,8 @@ ...@@ -16,7 +16,8 @@
"bin", "bin",
"config", "config",
"scripts", "scripts",
"template" "template",
"utils"
], ],
"bin": { "bin": {
"react-scripts": "./bin/react-scripts.js" "react-scripts": "./bin/react-scripts.js"
...@@ -53,10 +54,10 @@ ...@@ -53,10 +54,10 @@
"jest": "15.1.1", "jest": "15.1.1",
"json-loader": "0.5.4", "json-loader": "0.5.4",
"object-assign": "4.1.0", "object-assign": "4.1.0",
"opn": "4.0.2",
"path-exists": "2.1.0", "path-exists": "2.1.0",
"postcss-loader": "0.13.0", "postcss-loader": "0.13.0",
"promise": "7.1.1", "promise": "7.1.1",
"react-dev-utils": "0.1.0",
"recursive-readdir": "2.0.0", "recursive-readdir": "2.0.0",
"rimraf": "2.5.4", "rimraf": "2.5.4",
"strip-ansi": "3.0.1", "strip-ansi": "3.0.1",
......
...@@ -27,11 +27,14 @@ var rimrafSync = require('rimraf').sync; ...@@ -27,11 +27,14 @@ var rimrafSync = require('rimraf').sync;
var webpack = require('webpack'); var webpack = require('webpack');
var config = require('../config/webpack.config.prod'); var config = require('../config/webpack.config.prod');
var paths = require('../config/paths'); var paths = require('../config/paths');
var checkRequiredFiles = require('./utils/checkRequiredFiles'); var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
var recursive = require('recursive-readdir'); var recursive = require('recursive-readdir');
var stripAnsi = require('strip-ansi'); var stripAnsi = require('strip-ansi');
checkRequiredFiles(); // Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Input: /User/dan/app/build/static/js/main.82be8.js // Input: /User/dan/app/build/static/js/main.82be8.js
// Output: /static/js/main.js // Output: /static/js/main.js
......
...@@ -7,10 +7,10 @@ ...@@ -7,10 +7,10 @@
* of patent rights can be found in the PATENTS file in the same directory. * of patent rights can be found in the PATENTS file in the same directory.
*/ */
var createJestConfig = require('./utils/createJestConfig'); var createJestConfig = require('../utils/createJestConfig');
var fs = require('fs'); var fs = require('fs');
var path = require('path'); var path = require('path');
var prompt = require('./utils/prompt'); var prompt = require('react-dev-utils/prompt');
var rimrafSync = require('rimraf').sync; var rimrafSync = require('rimraf').sync;
var spawnSync = require('cross-spawn').sync; var spawnSync = require('cross-spawn').sync;
...@@ -31,6 +31,7 @@ prompt( ...@@ -31,6 +31,7 @@ prompt(
var files = [ var files = [
'.babelrc', '.babelrc',
'.eslintrc', '.eslintrc',
path.join('config', 'env.js'),
path.join('config', 'paths.js'), path.join('config', 'paths.js'),
path.join('config', 'polyfills.js'), path.join('config', 'polyfills.js'),
path.join('config', 'webpack.config.dev.js'), path.join('config', 'webpack.config.dev.js'),
...@@ -39,13 +40,7 @@ prompt( ...@@ -39,13 +40,7 @@ prompt(
path.join('config', 'jest', 'FileStub.js'), path.join('config', 'jest', 'FileStub.js'),
path.join('scripts', 'build.js'), path.join('scripts', 'build.js'),
path.join('scripts', 'start.js'), path.join('scripts', 'start.js'),
path.join('scripts', 'test.js'), path.join('scripts', 'test.js')
path.join('scripts', 'utils', 'checkRequiredFiles.js'),
path.join('scripts', 'utils', 'chrome.applescript'),
path.join('scripts', 'utils', 'getClientEnvironment.js'),
path.join('scripts', 'utils', 'InterpolateHtmlPlugin.js'),
path.join('scripts', 'utils', 'prompt.js'),
path.join('scripts', 'utils', 'WatchMissingNodeModulesPlugin.js')
]; ];
// Ensure that the app folder is clean and we won't override any files // Ensure that the app folder is clean and we won't override any files
...@@ -65,7 +60,6 @@ prompt( ...@@ -65,7 +60,6 @@ prompt(
fs.mkdirSync(path.join(appPath, 'config')); fs.mkdirSync(path.join(appPath, 'config'));
fs.mkdirSync(path.join(appPath, 'config', 'jest')); fs.mkdirSync(path.join(appPath, 'config', 'jest'));
fs.mkdirSync(path.join(appPath, 'scripts')); fs.mkdirSync(path.join(appPath, 'scripts'));
fs.mkdirSync(path.join(appPath, 'scripts', 'utils'));
files.forEach(function(file) { files.forEach(function(file) {
console.log('Copying ' + file + ' to ' + appPath); console.log('Copying ' + file + ' to ' + appPath);
......
...@@ -17,20 +17,25 @@ process.env.NODE_ENV = 'development'; ...@@ -17,20 +17,25 @@ process.env.NODE_ENV = 'development';
// https://github.com/motdotla/dotenv // https://github.com/motdotla/dotenv
require('dotenv').config({silent: true}); require('dotenv').config({silent: true});
var path = require('path');
var chalk = require('chalk'); var chalk = require('chalk');
var webpack = require('webpack'); var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server'); var WebpackDevServer = require('webpack-dev-server');
var historyApiFallback = require('connect-history-api-fallback'); var historyApiFallback = require('connect-history-api-fallback');
var httpProxyMiddleware = require('http-proxy-middleware'); var httpProxyMiddleware = require('http-proxy-middleware');
var execSync = require('child_process').execSync;
var opn = require('opn');
var detect = require('detect-port'); var detect = require('detect-port');
var checkRequiredFiles = require('./utils/checkRequiredFiles'); var clearConsole = require('react-dev-utils/clearConsole');
var prompt = require('./utils/prompt'); var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
var openBrowser = require('react-dev-utils/openBrowser');
var prompt = require('react-dev-utils/prompt');
var config = require('../config/webpack.config.dev'); var config = require('../config/webpack.config.dev');
var paths = require('../config/paths'); var paths = require('../config/paths');
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this. // Tools like Cloud9 rely on this.
var DEFAULT_PORT = process.env.PORT || 3000; var DEFAULT_PORT = process.env.PORT || 3000;
var compiler; var compiler;
...@@ -49,40 +54,6 @@ if (isSmokeTest) { ...@@ -49,40 +54,6 @@ if (isSmokeTest) {
}; };
} }
// 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!', '');
}
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;
}
function setupCompiler(host, port, protocol) { function setupCompiler(host, port, protocol) {
// "Compiler" is a low-level interface to Webpack. // "Compiler" is a low-level interface to Webpack.
// It lets us listen to some events and provide our own custom messages. // It lets us listen to some events and provide our own custom messages.
...@@ -101,9 +72,12 @@ function setupCompiler(host, port, protocol) { ...@@ -101,9 +72,12 @@ function setupCompiler(host, port, protocol) {
// Whether or not you have warnings or errors, you will get this event. // Whether or not you have warnings or errors, you will get this event.
compiler.plugin('done', function(stats) { compiler.plugin('done', function(stats) {
clearConsole(); clearConsole();
var hasErrors = stats.hasErrors();
var hasWarnings = stats.hasWarnings(); // We have switched off the default Webpack output in WebpackDevServer
if (!hasErrors && !hasWarnings) { // options so we are going to "massage" the warnings and errors and present
// them in a readable focused way.
var messages = formatWebpackMessages(stats);
if (!messages.errors.length && !messages.warnings.length) {
console.log(chalk.green('Compiled successfully!')); console.log(chalk.green('Compiled successfully!'));
console.log(); console.log();
console.log('The app is running at:'); console.log('The app is running at:');
...@@ -113,41 +87,24 @@ function setupCompiler(host, port, protocol) { ...@@ -113,41 +87,24 @@ function setupCompiler(host, port, protocol) {
console.log('Note that the development build is not optimized.'); console.log('Note that the development build is not optimized.');
console.log('To create a production build, use ' + chalk.cyan('npm run build') + '.'); console.log('To create a production build, use ' + chalk.cyan('npm run build') + '.');
console.log(); console.log();
return;
} }
// We have switched off the default Webpack output in WebpackDevServer // If errors exist, only show errors.
// options so we are going to "massage" the warnings and errors and present if (messages.errors.length) {
// them in a readable focused way.
// 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)
);
if (hasErrors) {
console.log(chalk.red('Failed to compile.')); console.log(chalk.red('Failed to compile.'));
console.log(); console.log();
if (formattedErrors.some(isLikelyASyntaxError)) { messages.errors.forEach(message => {
// If there are any syntax errors, show just them.
// This prevents a confusing ESLint parsing error
// preceding a much more useful Babel syntax error.
formattedErrors = formattedErrors.filter(isLikelyASyntaxError);
}
formattedErrors.forEach(message => {
console.log(message); console.log(message);
console.log(); console.log();
}); });
// If errors exist, ignore warnings.
return; return;
} }
if (hasWarnings) {
// Show warnings if no errors were found.
if (messages.warnings.length) {
console.log(chalk.yellow('Compiled with warnings.')); console.log(chalk.yellow('Compiled with warnings.'));
console.log(); console.log();
formattedWarnings.forEach(message => { messages.warnings.forEach(message => {
console.log(message); console.log(message);
console.log(); console.log();
}); });
...@@ -159,30 +116,6 @@ function setupCompiler(host, port, protocol) { ...@@ -159,30 +116,6 @@ function setupCompiler(host, port, protocol) {
}); });
} }
function openBrowser(host, port, protocol) {
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 ' + protocol + '://' + host + ':' + port + '/',
{cwd: path.join(__dirname, 'utils'), stdio: 'ignore'}
);
return;
} catch (err) {
// Ignore errors.
}
}
// Fallback to opn
// (It will always open new tab)
try {
opn(protocol + '://' + host + ':' + port + '/');
} catch (err) {
// Ignore errors.
}
}
// We need to provide a custom onError function for httpProxyMiddleware. // We need to provide a custom onError function for httpProxyMiddleware.
// It allows us to log custom error messages on the console. // It allows us to log custom error messages on the console.
function onProxyError(proxy) { function onProxyError(proxy) {
...@@ -314,14 +247,13 @@ function runDevServer(host, port, protocol) { ...@@ -314,14 +247,13 @@ function runDevServer(host, port, protocol) {
clearConsole(); clearConsole();
console.log(chalk.cyan('Starting the development server...')); console.log(chalk.cyan('Starting the development server...'));
console.log(); console.log();
openBrowser(host, port, protocol); openBrowser(protocol + '://' + host + ':' + port + '/');
}); });
} }
function run(port) { function run(port) {
var protocol = process.env.HTTPS === 'true' ? "https" : "http"; var protocol = process.env.HTTPS === 'true' ? "https" : "http";
var host = process.env.HOST || 'localhost'; var host = process.env.HOST || 'localhost';
checkRequiredFiles();
setupCompiler(host, port, protocol); setupCompiler(host, port, protocol);
runDevServer(host, port, protocol); runDevServer(host, port, protocol);
} }
......
...@@ -28,7 +28,7 @@ if (!process.env.CI) { ...@@ -28,7 +28,7 @@ if (!process.env.CI) {
// @remove-on-eject-begin // @remove-on-eject-begin
// This is not necessary after eject because we embed config into package.json. // This is not necessary after eject because we embed config into package.json.
const createJestConfig = require('./utils/createJestConfig'); const createJestConfig = require('../utils/createJestConfig');
const path = require('path'); const path = require('path');
const paths = require('../config/paths'); const paths = require('../config/paths');
argv.push('--config', JSON.stringify(createJestConfig( argv.push('--config', JSON.stringify(createJestConfig(
......
// @remove-on-eject-begin
/** /**
* Copyright (c) 2015-present, Facebook, Inc. * Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved. * All rights reserved.
...@@ -7,10 +6,11 @@ ...@@ -7,10 +6,11 @@
* LICENSE file in the root directory of this source tree. An additional grant * 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. * of patent rights can be found in the PATENTS file in the same directory.
*/ */
// @remove-on-eject-end
// Note: this file does not exist after ejecting.
const pathExists = require('path-exists'); const pathExists = require('path-exists');
const paths = require('../../config/paths'); const paths = require('../config/paths');
module.exports = (resolve, rootDir, isEjecting) => { module.exports = (resolve, rootDir, isEjecting) => {
const setupFiles = [resolve('config/polyfills.js')]; const setupFiles = [resolve('config/polyfills.js')];
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment