Use new .hooks api instead of .plugin for start script
This commit is contained in:
parent
7a585343b4
commit
822692dde8
260
scripts/start.js
260
scripts/start.js
|
@ -1,180 +1,174 @@
|
||||||
/*eslint-disable*/
|
/*eslint-disable*/
|
||||||
process.env.NODE_ENV = 'development';
|
process.env.NODE_ENV = 'development'
|
||||||
|
|
||||||
// Load environment variables from .env file. Suppress warnings using silent
|
// Load environment variables from .env file. Suppress warnings using silent
|
||||||
// if this file is missing. dotenv will never modify any environment variables
|
// if this file is missing. dotenv will never modify any environment variables
|
||||||
// that have already been set.
|
// that have already been set.
|
||||||
// https://github.com/motdotla/dotenv
|
// https://github.com/motdotla/dotenv
|
||||||
require('dotenv').config({silent: true});
|
require('dotenv').config({ silent: true })
|
||||||
|
|
||||||
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 detect = require('detect-port');
|
var detect = require('detect-port')
|
||||||
var clearConsole = require('react-dev-utils/clearConsole');
|
var clearConsole = require('react-dev-utils/clearConsole')
|
||||||
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
|
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles')
|
||||||
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
|
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages')
|
||||||
var getProcessForPort = require('react-dev-utils/getProcessForPort');
|
var getProcessForPort = require('react-dev-utils/getProcessForPort')
|
||||||
var openBrowser = require('react-dev-utils/openBrowser');
|
var openBrowser = require('react-dev-utils/openBrowser')
|
||||||
var pathExists = require('path-exists');
|
var pathExists = require('path-exists')
|
||||||
var config = require('../config/webpack.config.dev');
|
var config = require('../config/webpack.config.dev')
|
||||||
var paths = require('../config/paths');
|
var paths = require('../config/paths')
|
||||||
|
|
||||||
var useYarn = pathExists.sync(paths.yarnLockFile);
|
var useYarn = pathExists.sync(paths.yarnLockFile)
|
||||||
var cli = useYarn ? 'yarn' : 'npm';
|
var cli = useYarn ? 'yarn' : 'npm'
|
||||||
var isInteractive = process.stdout.isTTY;
|
var isInteractive = process.stdout.isTTY
|
||||||
|
|
||||||
// Warn and crash if required files are missing
|
// Warn and crash if required files are missing
|
||||||
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
|
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
|
||||||
process.exit(1);
|
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
|
||||||
var handleCompile;
|
var handleCompile
|
||||||
|
|
||||||
// You can safely remove this after ejecting.
|
|
||||||
// We only use this block for testing of Create React App itself:
|
|
||||||
var isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1);
|
|
||||||
if (isSmokeTest) {
|
|
||||||
handleCompile = function (err, stats) {
|
|
||||||
if (err || stats.hasErrors() || stats.hasWarnings()) {
|
|
||||||
process.exit(1);
|
|
||||||
} else {
|
|
||||||
process.exit(0);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
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.
|
||||||
compiler = webpack(config, handleCompile);
|
compiler = webpack(config, handleCompile)
|
||||||
|
|
||||||
// "invalid" event fires when you have changed a file, and Webpack is
|
// "invalid" event fires when you have changed a file, and Webpack is
|
||||||
// recompiling a bundle. WebpackDevServer takes care to pause serving the
|
// recompiling a bundle. WebpackDevServer takes care to pause serving the
|
||||||
// bundle, so if you refresh, it'll wait instead of serving the old one.
|
// bundle, so if you refresh, it'll wait instead of serving the old one.
|
||||||
// "invalid" is short for "bundle invalidated", it doesn't imply any errors.
|
// "invalid" is short for "bundle invalidated", it doesn't imply any errors.
|
||||||
compiler.plugin('invalid', function() {
|
compiler.hooks.invalid.tap('invalid', () => {
|
||||||
if (isInteractive) {
|
if (isInteractive) {
|
||||||
clearConsole();
|
clearConsole()
|
||||||
}
|
}
|
||||||
console.log('Compiling...');
|
console.log('Compiling...')
|
||||||
});
|
})
|
||||||
|
|
||||||
var isFirstCompile = true;
|
var isFirstCompile = true
|
||||||
|
|
||||||
// "done" event fires when Webpack has finished recompiling the bundle.
|
// "done" event fires when Webpack has finished recompiling the bundle.
|
||||||
// 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.hooks.done.tap('done', function(stats) {
|
||||||
if (isInteractive) {
|
if (isInteractive) {
|
||||||
clearConsole();
|
clearConsole()
|
||||||
}
|
}
|
||||||
|
|
||||||
// We have switched off the default Webpack output in WebpackDevServer
|
// We have switched off the default Webpack output in WebpackDevServer
|
||||||
// options so we are going to "massage" the warnings and errors and present
|
// options so we are going to "massage" the warnings and errors and present
|
||||||
// them in a readable focused way.
|
// them in a readable focused way.
|
||||||
var messages = formatWebpackMessages(stats.toJson({}, true));
|
var messages = formatWebpackMessages(stats.toJson({}, true))
|
||||||
var isSuccessful = !messages.errors.length && !messages.warnings.length;
|
var isSuccessful = !messages.errors.length && !messages.warnings.length
|
||||||
var showInstructions = isSuccessful && (isInteractive || isFirstCompile);
|
var showInstructions = isSuccessful && (isInteractive || isFirstCompile)
|
||||||
|
|
||||||
if (isSuccessful) {
|
if (isSuccessful) {
|
||||||
console.log(chalk.green('Compiled successfully!'));
|
console.log(chalk.green('Compiled successfully!'))
|
||||||
}
|
}
|
||||||
|
|
||||||
if (showInstructions) {
|
if (showInstructions) {
|
||||||
console.log();
|
console.log()
|
||||||
console.log('The app is running at:');
|
console.log('The app is running at:')
|
||||||
console.log();
|
console.log()
|
||||||
console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/'));
|
console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/'))
|
||||||
console.log();
|
console.log()
|
||||||
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(cli + ' run build') + '.');
|
console.log('To create a production build, use ' + chalk.cyan(cli + ' run build') + '.')
|
||||||
console.log();
|
console.log()
|
||||||
isFirstCompile = false;
|
isFirstCompile = false
|
||||||
}
|
}
|
||||||
|
|
||||||
// If errors exist, only show errors.
|
// If errors exist, only show errors.
|
||||||
if (messages.errors.length) {
|
if (messages.errors.length) {
|
||||||
console.log(chalk.red('Failed to compile.'));
|
console.log(chalk.red('Failed to compile.'))
|
||||||
console.log();
|
console.log()
|
||||||
messages.errors.forEach(message => {
|
messages.errors.forEach(message => {
|
||||||
console.log(message);
|
console.log(message)
|
||||||
console.log();
|
console.log()
|
||||||
});
|
})
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show warnings if no errors were found.
|
// Show warnings if no errors were found.
|
||||||
if (messages.warnings.length) {
|
if (messages.warnings.length) {
|
||||||
console.log(chalk.yellow('Compiled with warnings.'));
|
console.log(chalk.yellow('Compiled with warnings.'))
|
||||||
console.log();
|
console.log()
|
||||||
messages.warnings.forEach(message => {
|
messages.warnings.forEach(message => {
|
||||||
console.log(message);
|
console.log(message)
|
||||||
console.log();
|
console.log()
|
||||||
});
|
})
|
||||||
// Teach some ESLint tricks.
|
// Teach some ESLint tricks.
|
||||||
console.log('You may use special comments to disable some warnings.');
|
console.log('You may use special comments to disable some warnings.')
|
||||||
console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.');
|
console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.')
|
||||||
console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.');
|
console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.')
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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) {
|
||||||
return function(err, req, res){
|
return function(err, req, res) {
|
||||||
var host = req.headers && req.headers.host;
|
var host = req.headers && req.headers.host
|
||||||
console.log(
|
console.log(
|
||||||
chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) +
|
chalk.red('Proxy error:') +
|
||||||
' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.'
|
' Could not proxy request ' +
|
||||||
);
|
chalk.cyan(req.url) +
|
||||||
|
' from ' +
|
||||||
|
chalk.cyan(host) +
|
||||||
|
' to ' +
|
||||||
|
chalk.cyan(proxy) +
|
||||||
|
'.',
|
||||||
|
)
|
||||||
console.log(
|
console.log(
|
||||||
'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
|
'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
|
||||||
chalk.cyan(err.code) + ').'
|
chalk.cyan(err.code) +
|
||||||
);
|
').',
|
||||||
console.log();
|
)
|
||||||
|
console.log()
|
||||||
|
|
||||||
// And immediately send the proper error response to the client.
|
// And immediately send the proper error response to the client.
|
||||||
// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
|
// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
|
||||||
if (res.writeHead && !res.headersSent) {
|
if (res.writeHead && !res.headersSent) {
|
||||||
res.writeHead(500);
|
res.writeHead(500)
|
||||||
}
|
}
|
||||||
res.end('Proxy error: Could not proxy request ' + req.url + ' from ' +
|
res.end(
|
||||||
host + ' to ' + proxy + ' (' + err.code + ').'
|
'Proxy error: Could not proxy request ' + req.url + ' from ' + host + ' to ' + proxy + ' (' + err.code + ').',
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function addMiddleware(devServer) {
|
function addMiddleware(devServer) {
|
||||||
// `proxy` lets you to specify a fallback server during development.
|
// `proxy` lets you to specify a fallback server during development.
|
||||||
// Every unrecognized request will be forwarded to it.
|
// Every unrecognized request will be forwarded to it.
|
||||||
var proxy = require(paths.appPackageJson).proxy;
|
var proxy = require(paths.appPackageJson).proxy
|
||||||
devServer.use(historyApiFallback({
|
devServer.use(
|
||||||
// Paths with dots should still use the history fallback.
|
historyApiFallback({
|
||||||
// See https://github.com/facebookincubator/create-react-app/issues/387.
|
// Paths with dots should still use the history fallback.
|
||||||
disableDotRule: true,
|
// See https://github.com/facebookincubator/create-react-app/issues/387.
|
||||||
// For single page apps, we generally want to fallback to /index.html.
|
disableDotRule: true,
|
||||||
// However we also want to respect `proxy` for API calls.
|
// For single page apps, we generally want to fallback to /index.html.
|
||||||
// So if `proxy` is specified, we need to decide which fallback to use.
|
// However we also want to respect `proxy` for API calls.
|
||||||
// We use a heuristic: if request `accept`s text/html, we pick /index.html.
|
// So if `proxy` is specified, we need to decide which fallback to use.
|
||||||
// Modern browsers include text/html into `accept` header when navigating.
|
// We use a heuristic: if request `accept`s text/html, we pick /index.html.
|
||||||
// However API calls like `fetch()` won’t generally accept text/html.
|
// Modern browsers include text/html into `accept` header when navigating.
|
||||||
// If this heuristic doesn’t work well for you, don’t use `proxy`.
|
// However API calls like `fetch()` won’t generally accept text/html.
|
||||||
htmlAcceptHeaders: proxy ?
|
// If this heuristic doesn’t work well for you, don’t use `proxy`.
|
||||||
['text/html'] :
|
htmlAcceptHeaders: proxy ? ['text/html'] : ['text/html', '*/*'],
|
||||||
['text/html', '*/*']
|
}),
|
||||||
}));
|
)
|
||||||
if (proxy) {
|
if (proxy) {
|
||||||
if (typeof proxy !== 'string') {
|
if (typeof proxy !== 'string') {
|
||||||
console.log(chalk.red('When specified, "proxy" in package.json must be a string.'));
|
console.log(chalk.red('When specified, "proxy" in package.json must be a string.'))
|
||||||
console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'));
|
console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'))
|
||||||
console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'));
|
console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'))
|
||||||
process.exit(1);
|
process.exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Otherwise, if proxy is specified, we will let it handle any request.
|
// Otherwise, if proxy is specified, we will let it handle any request.
|
||||||
|
@ -183,7 +177,7 @@ function addMiddleware(devServer) {
|
||||||
// - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
|
// - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
|
||||||
// - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
|
// - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
|
||||||
// Tip: use https://jex.im/regulex/ to visualize the regex
|
// Tip: use https://jex.im/regulex/ to visualize the regex
|
||||||
var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/;
|
var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/
|
||||||
|
|
||||||
// Pass the scope regex both to Express and to the middleware for proxying
|
// Pass the scope regex both to Express and to the middleware for proxying
|
||||||
// of both HTTP and WebSockets to work without false positives.
|
// of both HTTP and WebSockets to work without false positives.
|
||||||
|
@ -195,25 +189,25 @@ function addMiddleware(devServer) {
|
||||||
// requests. To prevent CORS issues, we have to change
|
// requests. To prevent CORS issues, we have to change
|
||||||
// the Origin to match the target URL.
|
// the Origin to match the target URL.
|
||||||
if (proxyReq.getHeader('origin')) {
|
if (proxyReq.getHeader('origin')) {
|
||||||
proxyReq.setHeader('origin', proxy);
|
proxyReq.setHeader('origin', proxy)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onError: onProxyError(proxy),
|
onError: onProxyError(proxy),
|
||||||
secure: false,
|
secure: false,
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
ws: true
|
ws: true,
|
||||||
});
|
})
|
||||||
devServer.use(mayProxy, hpm);
|
devServer.use(mayProxy, hpm)
|
||||||
|
|
||||||
// Listen for the websocket 'upgrade' event and upgrade the connection.
|
// Listen for the websocket 'upgrade' event and upgrade the connection.
|
||||||
// If this is not done, httpProxyMiddleware will not try to upgrade until
|
// If this is not done, httpProxyMiddleware will not try to upgrade until
|
||||||
// an initial plain HTTP request is made.
|
// an initial plain HTTP request is made.
|
||||||
devServer.listeningApp.on('upgrade', hpm.upgrade);
|
devServer.listeningApp.on('upgrade', hpm.upgrade)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Finally, by now we have certainly resolved the URL.
|
// Finally, by now we have certainly resolved the URL.
|
||||||
// It may be /index.html, so let the dev server try serving it again.
|
// It may be /index.html, so let the dev server try serving it again.
|
||||||
devServer.use(devServer.middleware);
|
devServer.use(devServer.middleware)
|
||||||
}
|
}
|
||||||
|
|
||||||
function runDevServer(host, port, protocol) {
|
function runDevServer(host, port, protocol) {
|
||||||
|
@ -253,54 +247,54 @@ function runDevServer(host, port, protocol) {
|
||||||
// Reportedly, this avoids CPU overload on some systems.
|
// Reportedly, this avoids CPU overload on some systems.
|
||||||
// https://github.com/facebookincubator/create-react-app/issues/293
|
// https://github.com/facebookincubator/create-react-app/issues/293
|
||||||
watchOptions: {
|
watchOptions: {
|
||||||
ignored: /node_modules/
|
ignored: /node_modules/,
|
||||||
},
|
},
|
||||||
// Enable HTTPS if the HTTPS environment variable is set to 'true'
|
// Enable HTTPS if the HTTPS environment variable is set to 'true'
|
||||||
https: protocol === "https",
|
https: protocol === 'https',
|
||||||
host: host
|
host: host,
|
||||||
});
|
})
|
||||||
|
|
||||||
// Our custom middleware proxies requests to /index.html or a remote API.
|
// Our custom middleware proxies requests to /index.html or a remote API.
|
||||||
addMiddleware(devServer);
|
addMiddleware(devServer)
|
||||||
|
|
||||||
// Launch WebpackDevServer.
|
// Launch WebpackDevServer.
|
||||||
devServer.listen(port, (err, result) => {
|
devServer.listen(port, (err, result) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
return console.log(err);
|
return console.log(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isInteractive) {
|
if (isInteractive) {
|
||||||
clearConsole();
|
clearConsole()
|
||||||
}
|
}
|
||||||
console.log(chalk.cyan('Starting the development server...'));
|
console.log(chalk.cyan('Starting the development server...'))
|
||||||
console.log();
|
console.log()
|
||||||
|
|
||||||
if (isInteractive) {
|
if (isInteractive) {
|
||||||
openBrowser(protocol + '://' + host + ':' + port + '/');
|
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'
|
||||||
setupCompiler(host, port, protocol);
|
setupCompiler(host, port, protocol)
|
||||||
runDevServer(host, port, protocol);
|
runDevServer(host, port, protocol)
|
||||||
}
|
}
|
||||||
|
|
||||||
// We attempt to use the default port but if it is busy, we offer the user to
|
// We attempt to use the default port but if it is busy, we offer the user to
|
||||||
// run on a different port. `detect()` Promise resolves to the next free port.
|
// run on a different port. `detect()` Promise resolves to the next free port.
|
||||||
detect(DEFAULT_PORT).then(port => {
|
detect(DEFAULT_PORT).then(port => {
|
||||||
if (port === DEFAULT_PORT) {
|
if (port === DEFAULT_PORT) {
|
||||||
run(port);
|
run(port)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isInteractive) {
|
if (isInteractive) {
|
||||||
clearConsole();
|
clearConsole()
|
||||||
var existingProcess = getProcessForPort(DEFAULT_PORT);
|
var existingProcess = getProcessForPort(DEFAULT_PORT)
|
||||||
run(port);
|
run(port)
|
||||||
} else {
|
} else {
|
||||||
console.log(chalk.red('Something is already running on port ' + DEFAULT_PORT + '.'));
|
console.log(chalk.red('Something is already running on port ' + DEFAULT_PORT + '.'))
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
Loading…
Reference in New Issue