Skip to content
  • Sponsor facebook/create-react-app

  • Notifications You must be signed in to change notification settings
  • Fork 27k

Commit b88d665

Browse files
djgrantTimer
authored andcommittedMar 4, 2017
Modularise scripts (#1433)
* Refactor start script into modules * Move dev server config into config file * Replace eject file whitelist with a "remove-file-on-eject" flag * Move utils into scripts folder (for inclusion in ejection) * Add missed changes * Pass showInstructions as an argument * Fix eject bug * Don't eject babelTransform
1 parent 59cab8f commit b88d665

9 files changed

+304
-275
lines changed
 

‎packages/react-scripts/config/jest/babelTransform.js

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// @remove-file-on-eject
12
/**
23
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
34
*
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
var config = require('./webpack.config.dev');
2+
var paths = require('./paths');
3+
4+
var protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
5+
var host = process.env.HOST || 'localhost';
6+
7+
module.exports = {
8+
// Enable gzip compression of generated files.
9+
compress: true,
10+
// Silence WebpackDevServer's own logs since they're generally not useful.
11+
// It will still show compile warnings and errors with this setting.
12+
clientLogLevel: 'none',
13+
// By default WebpackDevServer serves physical files from current directory
14+
// in addition to all the virtual build products that it serves from memory.
15+
// This is confusing because those files won’t automatically be available in
16+
// production build folder unless we copy them. However, copying the whole
17+
// project directory is dangerous because we may expose sensitive files.
18+
// Instead, we establish a convention that only files in `public` directory
19+
// get served. Our build script will copy `public` into the `build` folder.
20+
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
21+
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
22+
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
23+
// Note that we only recommend to use `public` folder as an escape hatch
24+
// for files like `favicon.ico`, `manifest.json`, and libraries that are
25+
// for some reason broken when imported through Webpack. If you just want to
26+
// use an image, put it in `src` and `import` it from JavaScript instead.
27+
contentBase: paths.appPublic,
28+
// By default files from `contentBase` will not trigger a page reload.
29+
watchContentBase: true,
30+
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
31+
// for the WebpackDevServer client so it can learn when the files were
32+
// updated. The WebpackDevServer client is included as an entry point
33+
// in the Webpack development configuration. Note that only changes
34+
// to CSS are currently hot reloaded. JS changes will refresh the browser.
35+
hot: true,
36+
// It is important to tell WebpackDevServer to use the same "root" path
37+
// as we specified in the config. In development, we always serve from /.
38+
publicPath: config.output.publicPath,
39+
// WebpackDevServer is noisy by default so we emit custom message instead
40+
// by listening to the compiler events with `compiler.plugin` calls above.
41+
quiet: true,
42+
// Reportedly, this avoids CPU overload on some systems.
43+
// https://github.com/facebookincubator/create-react-app/issues/293
44+
watchOptions: {
45+
ignored: /node_modules/
46+
},
47+
// Enable HTTPS if the HTTPS environment variable is set to 'true'
48+
https: protocol === 'https',
49+
host: host,
50+
overlay: false,
51+
};

‎packages/react-scripts/scripts/eject.js

+30-24
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// @remove-file-on-eject
12
/**
23
* Copyright (c) 2015-present, Facebook, Inc.
34
* All rights reserved.
@@ -7,13 +8,14 @@
78
* of patent rights can be found in the PATENTS file in the same directory.
89
*/
910

10-
var createJestConfig = require('../utils/createJestConfig');
1111
var fs = require('fs-extra');
1212
var path = require('path');
13-
var paths = require('../config/paths');
14-
var prompt = require('react-dev-utils/prompt');
1513
var spawnSync = require('cross-spawn').sync;
1614
var chalk = require('chalk');
15+
var prompt = require('react-dev-utils/prompt');
16+
var paths = require('../config/paths');
17+
var createJestConfig = require('./utils/createJestConfig');
18+
1719
var green = chalk.green;
1820
var cyan = chalk.cyan;
1921

@@ -45,44 +47,48 @@ prompt(
4547

4648
var folders = [
4749
'config',
48-
path.join('config', 'jest'),
49-
'scripts'
50+
'config/jest',
51+
'scripts',
52+
'scripts/utils',
5053
];
5154

52-
var files = [
53-
path.join('config', 'env.js'),
54-
path.join('config', 'paths.js'),
55-
path.join('config', 'polyfills.js'),
56-
path.join('config', 'webpack.config.dev.js'),
57-
path.join('config', 'webpack.config.prod.js'),
58-
path.join('config', 'jest', 'cssTransform.js'),
59-
path.join('config', 'jest', 'fileTransform.js'),
60-
path.join('scripts', 'build.js'),
61-
path.join('scripts', 'start.js'),
62-
path.join('scripts', 'test.js')
63-
];
55+
// Make shallow array of files paths
56+
var files = folders.reduce(function (files, folder) {
57+
return files.concat(
58+
fs.readdirSync(path.join(ownPath, folder))
59+
// set full path
60+
.map(file => path.join(ownPath, folder, file))
61+
// omit dirs from file list
62+
.filter(file => fs.lstatSync(file).isFile())
63+
);
64+
}, []);
6465

6566
// Ensure that the app folder is clean and we won't override any files
6667
folders.forEach(verifyAbsent);
6768
files.forEach(verifyAbsent);
6869

69-
// Copy the files over
70+
console.log();
71+
console.log(cyan('Copying files into ' + appPath));
72+
7073
folders.forEach(function(folder) {
7174
fs.mkdirSync(path.join(appPath, folder))
7275
});
7376

74-
console.log();
75-
console.log(cyan('Copying files into ' + appPath));
7677
files.forEach(function(file) {
77-
console.log(' Adding ' + cyan(file) + ' to the project');
78-
var content = fs
79-
.readFileSync(path.join(ownPath, file), 'utf8')
78+
var content = fs.readFileSync(file, 'utf8');
79+
80+
// Skip flagged files
81+
if (content.match(/\/\/ @remove-file-on-eject/)) {
82+
return;
83+
}
84+
content = content
8085
// Remove dead code from .js files on eject
8186
.replace(/\/\/ @remove-on-eject-begin([\s\S]*?)\/\/ @remove-on-eject-end/mg, '')
8287
// Remove dead code from .applescript files on eject
8388
.replace(/-- @remove-on-eject-begin([\s\S]*?)-- @remove-on-eject-end/mg, '')
8489
.trim() + '\n';
85-
fs.writeFileSync(path.join(appPath, file), content);
90+
console.log(' Adding ' + cyan(file.replace(ownPath, '')) + ' to the project');
91+
fs.writeFileSync(file.replace(ownPath, appPath), content);
8692
});
8793
console.log();
8894

‎packages/react-scripts/scripts/init.js

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// @remove-file-on-eject
12
/**
23
* Copyright (c) 2015-present, Facebook, Inc.
34
* All rights reserved.

‎packages/react-scripts/scripts/start.js

+23-247
Original file line numberDiff line numberDiff line change
@@ -17,21 +17,20 @@ process.env.NODE_ENV = 'development';
1717
// https://github.com/motdotla/dotenv
1818
require('dotenv').config({silent: true});
1919

20+
var fs = require('fs');
2021
var chalk = require('chalk');
21-
var webpack = require('webpack');
22-
var WebpackDevServer = require('webpack-dev-server');
23-
var historyApiFallback = require('connect-history-api-fallback');
24-
var httpProxyMiddleware = require('http-proxy-middleware');
2522
var detect = require('detect-port');
23+
var WebpackDevServer = require('webpack-dev-server');
2624
var clearConsole = require('react-dev-utils/clearConsole');
2725
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
28-
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
2926
var getProcessForPort = require('react-dev-utils/getProcessForPort');
3027
var openBrowser = require('react-dev-utils/openBrowser');
3128
var prompt = require('react-dev-utils/prompt');
32-
var fs = require('fs');
33-
var config = require('../config/webpack.config.dev');
3429
var paths = require('../config/paths');
30+
var config = require('../config/webpack.config.dev');
31+
var devServerConfig = require('../config/webpackDevServer.config');
32+
var createWebpackCompiler = require('./utils/createWebpackCompiler');
33+
var addWebpackMiddleware = require('./utils/addWebpackMiddleware');
3534

3635
var useYarn = fs.existsSync(paths.yarnLockFile);
3736
var cli = useYarn ? 'yarn' : 'npm';
@@ -44,247 +43,31 @@ if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
4443

4544
// Tools like Cloud9 rely on this.
4645
var DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
47-
var compiler;
48-
var handleCompile;
49-
50-
// You can safely remove this after ejecting.
51-
// We only use this block for testing of Create React App itself:
52-
var isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1);
53-
if (isSmokeTest) {
54-
handleCompile = function (err, stats) {
55-
if (err || stats.hasErrors() || stats.hasWarnings()) {
56-
process.exit(1);
57-
} else {
58-
process.exit(0);
59-
}
60-
};
61-
}
62-
63-
function setupCompiler(host, port, protocol) {
64-
// "Compiler" is a low-level interface to Webpack.
65-
// It lets us listen to some events and provide our own custom messages.
66-
try {
67-
compiler = webpack(config, handleCompile);
68-
} catch (err) {
69-
console.log(chalk.red('Failed to compile.'));
70-
console.log();
71-
console.log(err.message || err);
72-
console.log();
73-
process.exit(1);
74-
}
75-
76-
// "invalid" event fires when you have changed a file, and Webpack is
77-
// recompiling a bundle. WebpackDevServer takes care to pause serving the
78-
// bundle, so if you refresh, it'll wait instead of serving the old one.
79-
// "invalid" is short for "bundle invalidated", it doesn't imply any errors.
80-
compiler.plugin('invalid', function() {
81-
if (isInteractive) {
82-
clearConsole();
83-
}
84-
console.log('Compiling...');
85-
});
86-
87-
var isFirstCompile = true;
88-
89-
// "done" event fires when Webpack has finished recompiling the bundle.
90-
// Whether or not you have warnings or errors, you will get this event.
91-
compiler.plugin('done', function(stats) {
92-
if (isInteractive) {
93-
clearConsole();
94-
}
9546

96-
// We have switched off the default Webpack output in WebpackDevServer
97-
// options so we are going to "massage" the warnings and errors and present
98-
// them in a readable focused way.
99-
var messages = formatWebpackMessages(stats.toJson({}, true));
100-
var isSuccessful = !messages.errors.length && !messages.warnings.length;
101-
var showInstructions = isSuccessful && (isInteractive || isFirstCompile);
102-
103-
if (isSuccessful) {
104-
console.log(chalk.green('Compiled successfully!'));
105-
}
106-
107-
if (showInstructions) {
108-
console.log();
109-
console.log('The app is running at:');
110-
console.log();
111-
console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/'));
112-
console.log();
113-
console.log('Note that the development build is not optimized.');
114-
console.log('To create a production build, use ' + chalk.cyan(cli + ' run build') + '.');
115-
console.log();
116-
isFirstCompile = false;
117-
}
47+
function run(port) {
48+
var protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
49+
var host = process.env.HOST || 'localhost';
11850

119-
// If errors exist, only show errors.
120-
if (messages.errors.length) {
121-
console.log(chalk.red('Failed to compile.'));
122-
console.log();
123-
messages.errors.forEach(message => {
124-
console.log(message);
125-
console.log();
126-
});
51+
// Create a webpack compiler that is configured with custom messages.
52+
var compiler = createWebpackCompiler(config, function onReady(showInstructions) {
53+
if (!showInstructions) {
12754
return;
12855
}
129-
130-
// Show warnings if no errors were found.
131-
if (messages.warnings.length) {
132-
console.log(chalk.yellow('Compiled with warnings.'));
133-
console.log();
134-
messages.warnings.forEach(message => {
135-
console.log(message);
136-
console.log();
137-
});
138-
// Teach some ESLint tricks.
139-
console.log('You may use special comments to disable some warnings.');
140-
console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.');
141-
console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.');
142-
}
143-
});
144-
}
145-
146-
// We need to provide a custom onError function for httpProxyMiddleware.
147-
// It allows us to log custom error messages on the console.
148-
function onProxyError(proxy) {
149-
return function(err, req, res){
150-
var host = req.headers && req.headers.host;
151-
console.log(
152-
chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) +
153-
' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.'
154-
);
155-
console.log(
156-
'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
157-
chalk.cyan(err.code) + ').'
158-
);
15956
console.log();
160-
161-
// And immediately send the proper error response to the client.
162-
// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
163-
if (res.writeHead && !res.headersSent) {
164-
res.writeHead(500);
165-
}
166-
res.end('Proxy error: Could not proxy request ' + req.url + ' from ' +
167-
host + ' to ' + proxy + ' (' + err.code + ').'
168-
);
169-
}
170-
}
171-
172-
function addMiddleware(devServer) {
173-
// `proxy` lets you to specify a fallback server during development.
174-
// Every unrecognized request will be forwarded to it.
175-
var proxy = require(paths.appPackageJson).proxy;
176-
devServer.use(historyApiFallback({
177-
// Paths with dots should still use the history fallback.
178-
// See https://github.com/facebookincubator/create-react-app/issues/387.
179-
disableDotRule: true,
180-
// For single page apps, we generally want to fallback to /index.html.
181-
// However we also want to respect `proxy` for API calls.
182-
// So if `proxy` is specified, we need to decide which fallback to use.
183-
// We use a heuristic: if request `accept`s text/html, we pick /index.html.
184-
// Modern browsers include text/html into `accept` header when navigating.
185-
// However API calls like `fetch()` won’t generally accept text/html.
186-
// If this heuristic doesn’t work well for you, don’t use `proxy`.
187-
htmlAcceptHeaders: proxy ?
188-
['text/html'] :
189-
['text/html', '*/*']
190-
}));
191-
if (proxy) {
192-
if (typeof proxy !== 'string') {
193-
console.log(chalk.red('When specified, "proxy" in package.json must be a string.'));
194-
console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'));
195-
console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'));
196-
process.exit(1);
197-
}
198-
199-
// Otherwise, if proxy is specified, we will let it handle any request.
200-
// There are a few exceptions which we won't send to the proxy:
201-
// - /index.html (served as HTML5 history API fallback)
202-
// - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
203-
// - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
204-
// Tip: use https://jex.im/regulex/ to visualize the regex
205-
var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/;
206-
207-
// Pass the scope regex both to Express and to the middleware for proxying
208-
// of both HTTP and WebSockets to work without false positives.
209-
var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), {
210-
target: proxy,
211-
logLevel: 'silent',
212-
onProxyReq: function(proxyReq, req, res) {
213-
// Browers may send Origin headers even with same-origin
214-
// requests. To prevent CORS issues, we have to change
215-
// the Origin to match the target URL.
216-
if (proxyReq.getHeader('origin')) {
217-
proxyReq.setHeader('origin', proxy);
218-
}
219-
},
220-
onError: onProxyError(proxy),
221-
secure: false,
222-
changeOrigin: true,
223-
ws: true,
224-
xfwd: true
225-
});
226-
devServer.use(mayProxy, hpm);
227-
228-
// Listen for the websocket 'upgrade' event and upgrade the connection.
229-
// If this is not done, httpProxyMiddleware will not try to upgrade until
230-
// an initial plain HTTP request is made.
231-
devServer.listeningApp.on('upgrade', hpm.upgrade);
232-
}
233-
234-
// Finally, by now we have certainly resolved the URL.
235-
// It may be /index.html, so let the dev server try serving it again.
236-
devServer.use(devServer.middleware);
237-
}
238-
239-
function runDevServer(host, port, protocol) {
240-
var devServer = new WebpackDevServer(compiler, {
241-
// Enable gzip compression of generated files.
242-
compress: true,
243-
// Silence WebpackDevServer's own logs since they're generally not useful.
244-
// It will still show compile warnings and errors with this setting.
245-
clientLogLevel: 'none',
246-
// By default WebpackDevServer serves physical files from current directory
247-
// in addition to all the virtual build products that it serves from memory.
248-
// This is confusing because those files won’t automatically be available in
249-
// production build folder unless we copy them. However, copying the whole
250-
// project directory is dangerous because we may expose sensitive files.
251-
// Instead, we establish a convention that only files in `public` directory
252-
// get served. Our build script will copy `public` into the `build` folder.
253-
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
254-
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
255-
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
256-
// Note that we only recommend to use `public` folder as an escape hatch
257-
// for files like `favicon.ico`, `manifest.json`, and libraries that are
258-
// for some reason broken when imported through Webpack. If you just want to
259-
// use an image, put it in `src` and `import` it from JavaScript instead.
260-
contentBase: paths.appPublic,
261-
// By default files from `contentBase` will not trigger a page reload.
262-
watchContentBase: true,
263-
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
264-
// for the WebpackDevServer client so it can learn when the files were
265-
// updated. The WebpackDevServer client is included as an entry point
266-
// in the Webpack development configuration. Note that only changes
267-
// to CSS are currently hot reloaded. JS changes will refresh the browser.
268-
hot: true,
269-
// It is important to tell WebpackDevServer to use the same "root" path
270-
// as we specified in the config. In development, we always serve from /.
271-
publicPath: config.output.publicPath,
272-
// WebpackDevServer is noisy by default so we emit custom message instead
273-
// by listening to the compiler events with `compiler.plugin` calls above.
274-
quiet: true,
275-
// Reportedly, this avoids CPU overload on some systems.
276-
// https://github.com/facebookincubator/create-react-app/issues/293
277-
watchOptions: {
278-
ignored: /node_modules/
279-
},
280-
// Enable HTTPS if the HTTPS environment variable is set to 'true'
281-
https: protocol === "https",
282-
host: host,
283-
overlay: false,
57+
console.log('The app is running at:');
58+
console.log();
59+
console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/'));
60+
console.log();
61+
console.log('Note that the development build is not optimized.');
62+
console.log('To create a production build, use ' + chalk.cyan(cli + ' run build') + '.');
63+
console.log();
28464
});
28565

66+
// Serve webpack assets generated by the compiler over a web sever.
67+
var devServer = new WebpackDevServer(compiler, devServerConfig);
68+
28669
// Our custom middleware proxies requests to /index.html or a remote API.
287-
addMiddleware(devServer);
70+
addWebpackMiddleware(devServer);
28871

28972
// Launch WebpackDevServer.
29073
devServer.listen(port, (err, result) => {
@@ -302,13 +85,6 @@ function runDevServer(host, port, protocol) {
30285
});
30386
}
30487

305-
function run(port) {
306-
var protocol = process.env.HTTPS === 'true' ? "https" : "http";
307-
var host = process.env.HOST || 'localhost';
308-
setupCompiler(host, port, protocol);
309-
runDevServer(host, port, protocol);
310-
}
311-
31288
// We attempt to use the default port but if it is busy, we offer the user to
31389
// run on a different port. `detect()` Promise resolves to the next free port.
31490
detect(DEFAULT_PORT).then(port => {

‎packages/react-scripts/scripts/test.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ if (!process.env.CI && argv.indexOf('--coverage') < 0) {
2828

2929
// @remove-on-eject-begin
3030
// This is not necessary after eject because we embed config into package.json.
31-
const createJestConfig = require('../utils/createJestConfig');
31+
const createJestConfig = require('./utils/createJestConfig');
3232
const path = require('path');
3333
const paths = require('../config/paths');
3434
argv.push('--config', JSON.stringify(createJestConfig(
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
var chalk = require('chalk');
2+
var historyApiFallback = require('connect-history-api-fallback');
3+
var httpProxyMiddleware = require('http-proxy-middleware');
4+
var paths = require('../../config/paths');
5+
6+
// We need to provide a custom onError function for httpProxyMiddleware.
7+
// It allows us to log custom error messages on the console.
8+
function onProxyError(proxy) {
9+
return function(err, req, res){
10+
var host = req.headers && req.headers.host;
11+
console.log(
12+
chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) +
13+
' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.'
14+
);
15+
console.log(
16+
'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
17+
chalk.cyan(err.code) + ').'
18+
);
19+
console.log();
20+
21+
// And immediately send the proper error response to the client.
22+
// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
23+
if (res.writeHead && !res.headersSent) {
24+
res.writeHead(500);
25+
}
26+
res.end('Proxy error: Could not proxy request ' + req.url + ' from ' +
27+
host + ' to ' + proxy + ' (' + err.code + ').'
28+
);
29+
}
30+
}
31+
32+
module.exports = function addWebpackMiddleware(devServer) {
33+
// `proxy` lets you to specify a fallback server during development.
34+
// Every unrecognized request will be forwarded to it.
35+
var proxy = require(paths.appPackageJson).proxy;
36+
devServer.use(historyApiFallback({
37+
// Paths with dots should still use the history fallback.
38+
// See https://github.com/facebookincubator/create-react-app/issues/387.
39+
disableDotRule: true,
40+
// For single page apps, we generally want to fallback to /index.html.
41+
// However we also want to respect `proxy` for API calls.
42+
// So if `proxy` is specified, we need to decide which fallback to use.
43+
// We use a heuristic: if request `accept`s text/html, we pick /index.html.
44+
// Modern browsers include text/html into `accept` header when navigating.
45+
// However API calls like `fetch()` won’t generally accept text/html.
46+
// If this heuristic doesn’t work well for you, don’t use `proxy`.
47+
htmlAcceptHeaders: proxy ?
48+
['text/html'] :
49+
['text/html', '*/*']
50+
}));
51+
if (proxy) {
52+
if (typeof proxy !== 'string') {
53+
console.log(chalk.red('When specified, "proxy" in package.json must be a string.'));
54+
console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'));
55+
console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'));
56+
process.exit(1);
57+
}
58+
59+
// Otherwise, if proxy is specified, we will let it handle any request.
60+
// There are a few exceptions which we won't send to the proxy:
61+
// - /index.html (served as HTML5 history API fallback)
62+
// - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
63+
// - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
64+
// Tip: use https://jex.im/regulex/ to visualize the regex
65+
var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/;
66+
67+
// Pass the scope regex both to Express and to the middleware for proxying
68+
// of both HTTP and WebSockets to work without false positives.
69+
var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), {
70+
target: proxy,
71+
logLevel: 'silent',
72+
onProxyReq: function(proxyReq, req, res) {
73+
// Browers may send Origin headers even with same-origin
74+
// requests. To prevent CORS issues, we have to change
75+
// the Origin to match the target URL.
76+
if (proxyReq.getHeader('origin')) {
77+
proxyReq.setHeader('origin', proxy);
78+
}
79+
},
80+
onError: onProxyError(proxy),
81+
secure: false,
82+
changeOrigin: true,
83+
ws: true,
84+
xfwd: true
85+
});
86+
devServer.use(mayProxy, hpm);
87+
88+
// Listen for the websocket 'upgrade' event and upgrade the connection.
89+
// If this is not done, httpProxyMiddleware will not try to upgrade until
90+
// an initial plain HTTP request is made.
91+
devServer.listeningApp.on('upgrade', hpm.upgrade);
92+
}
93+
94+
// Finally, by now we have certainly resolved the URL.
95+
// It may be /index.html, so let the dev server try serving it again.
96+
devServer.use(devServer.middleware);
97+
};

‎packages/react-scripts/utils/createJestConfig.js ‎packages/react-scripts/scripts/utils/createJestConfig.js

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// @remove-file-on-eject
12
/**
23
* Copyright (c) 2015-present, Facebook, Inc.
34
* All rights reserved.
@@ -7,10 +8,8 @@
78
* of patent rights can be found in the PATENTS file in the same directory.
89
*/
910

10-
// Note: this file does not exist after ejecting.
11-
1211
const fs = require('fs');
13-
const paths = require('../config/paths');
12+
const paths = require('../../config/paths');
1413

1514
module.exports = (resolve, rootDir, isEjecting) => {
1615
// Use this instead of `paths.testsSetup` to avoid putting
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
var chalk = require('chalk');
2+
var webpack = require('webpack');
3+
var clearConsole = require('react-dev-utils/clearConsole');
4+
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
5+
6+
var isInteractive = process.stdout.isTTY;
7+
var handleCompile;
8+
9+
// You can safely remove this after ejecting.
10+
// We only use this block for testing of Create React App itself:
11+
var isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1);
12+
if (isSmokeTest) {
13+
handleCompile = function (err, stats) {
14+
if (err || stats.hasErrors() || stats.hasWarnings()) {
15+
process.exit(1);
16+
} else {
17+
process.exit(0);
18+
}
19+
};
20+
}
21+
22+
module.exports = function createWebpackCompiler(config, onReadyCallback) {
23+
// "Compiler" is a low-level interface to Webpack.
24+
// It lets us listen to some events and provide our own custom messages.
25+
try {
26+
var compiler = webpack(config, handleCompile);
27+
} catch (err) {
28+
console.log(chalk.red('Failed to compile.'));
29+
console.log();
30+
console.log(err.message || err);
31+
console.log();
32+
process.exit(1);
33+
}
34+
35+
// "invalid" event fires when you have changed a file, and Webpack is
36+
// recompiling a bundle. WebpackDevServer takes care to pause serving the
37+
// bundle, so if you refresh, it'll wait instead of serving the old one.
38+
// "invalid" is short for "bundle invalidated", it doesn't imply any errors.
39+
compiler.plugin('invalid', function() {
40+
if (isInteractive) {
41+
clearConsole();
42+
}
43+
console.log('Compiling...');
44+
});
45+
46+
var isFirstCompile = true;
47+
48+
// "done" event fires when Webpack has finished recompiling the bundle.
49+
// Whether or not you have warnings or errors, you will get this event.
50+
compiler.plugin('done', function(stats) {
51+
if (isInteractive) {
52+
clearConsole();
53+
}
54+
55+
// We have switched off the default Webpack output in WebpackDevServer
56+
// options so we are going to "massage" the warnings and errors and present
57+
// them in a readable focused way.
58+
var messages = formatWebpackMessages(stats.toJson({}, true));
59+
var isSuccessful = !messages.errors.length && !messages.warnings.length;
60+
var showInstructions = isSuccessful && (isInteractive || isFirstCompile);
61+
62+
if (isSuccessful) {
63+
console.log(chalk.green('Compiled successfully!'));
64+
}
65+
66+
if (typeof onReadyCallback === 'function') {
67+
onReadyCallback(showInstructions);
68+
}
69+
isFirstCompile = false;
70+
71+
// If errors exist, only show errors.
72+
if (messages.errors.length) {
73+
console.log(chalk.red('Failed to compile.'));
74+
console.log();
75+
messages.errors.forEach(message => {
76+
console.log(message);
77+
console.log();
78+
});
79+
return;
80+
}
81+
82+
// Show warnings if no errors were found.
83+
if (messages.warnings.length) {
84+
console.log(chalk.yellow('Compiled with warnings.'));
85+
console.log();
86+
messages.warnings.forEach(message => {
87+
console.log(message);
88+
console.log();
89+
});
90+
// Teach some ESLint tricks.
91+
console.log('You may use special comments to disable some warnings.');
92+
console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.');
93+
console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.');
94+
}
95+
});
96+
97+
return compiler;
98+
};

0 commit comments

Comments
 (0)
Please sign in to comment.