parent
73b3e2dbe8
commit
09ef94d9bc
@ -1,3 +1,11 @@
|
||||
{
|
||||
"typescript.tsdk": "node_modules\\typescript\\lib"
|
||||
"typescript.tsdk": "node_modules\\typescript\\lib",
|
||||
"files.exclude": {
|
||||
"*.vsix": true,
|
||||
"**/*.lock": true,
|
||||
"**/node_modules/": true,
|
||||
"dist/": true,
|
||||
"util/": true,
|
||||
"webview/build/": true
|
||||
}
|
||||
}
|
@ -1,149 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var chalk = require('chalk');
|
||||
var filesize = require('filesize');
|
||||
var recursive = require('recursive-readdir');
|
||||
var stripAnsi = require('strip-ansi');
|
||||
var gzipSize = require('gzip-size').sync;
|
||||
|
||||
// Prints a detailed summary of build files.
|
||||
function printFileSizesAfterBuild(
|
||||
webpackStats,
|
||||
previousSizeMap,
|
||||
buildFolder,
|
||||
maxBundleGzipSize,
|
||||
maxChunkGzipSize
|
||||
) {
|
||||
var root = previousSizeMap.root;
|
||||
var sizes = previousSizeMap.sizes;
|
||||
var assets = (webpackStats.stats || [webpackStats])
|
||||
.map(stats =>
|
||||
stats
|
||||
.toJson()
|
||||
.assets.filter(asset => /\.(js|css)$/.test(asset.name))
|
||||
.map(asset => {
|
||||
var fileContents = fs.readFileSync(path.join(root, asset.name));
|
||||
var size = gzipSize(fileContents);
|
||||
var previousSize = sizes[removeFileNameHash(root, asset.name)];
|
||||
var difference = getDifferenceLabel(size, previousSize);
|
||||
return {
|
||||
folder: path.join(
|
||||
path.basename(buildFolder),
|
||||
path.dirname(asset.name)
|
||||
),
|
||||
name: path.basename(asset.name),
|
||||
size: size,
|
||||
sizeLabel:
|
||||
filesize(size) + (difference ? ' (' + difference + ')' : '')
|
||||
};
|
||||
})
|
||||
)
|
||||
.reduce((single, all) => all.concat(single), []);
|
||||
assets.sort((a, b) => b.size - a.size);
|
||||
var longestSizeLabelLength = Math.max.apply(
|
||||
null,
|
||||
assets.map(a => stripAnsi(a.sizeLabel).length)
|
||||
);
|
||||
var suggestBundleSplitting = false;
|
||||
assets.forEach(asset => {
|
||||
var sizeLabel = asset.sizeLabel;
|
||||
var sizeLength = stripAnsi(sizeLabel).length;
|
||||
if (sizeLength < longestSizeLabelLength) {
|
||||
var rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength);
|
||||
sizeLabel += rightPadding;
|
||||
}
|
||||
var isMainBundle = asset.name.indexOf('main.') === 0;
|
||||
var maxRecommendedSize = isMainBundle
|
||||
? maxBundleGzipSize
|
||||
: maxChunkGzipSize;
|
||||
var isLarge = maxRecommendedSize && asset.size > maxRecommendedSize;
|
||||
if (isLarge && path.extname(asset.name) === '.js') {
|
||||
suggestBundleSplitting = true;
|
||||
}
|
||||
console.log(
|
||||
' ' +
|
||||
(isLarge ? chalk.yellow(sizeLabel) : sizeLabel) +
|
||||
' ' +
|
||||
chalk.dim(asset.folder + path.sep) +
|
||||
chalk.cyan(asset.name)
|
||||
);
|
||||
});
|
||||
if (suggestBundleSplitting) {
|
||||
console.log();
|
||||
console.log(
|
||||
chalk.yellow('The bundle size is significantly larger than recommended.')
|
||||
);
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'Consider reducing it with code splitting: https://goo.gl/9VhYWB'
|
||||
)
|
||||
);
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'You can also analyze the project dependencies: https://goo.gl/LeUzfb'
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function removeFileNameHash(buildFolder, fileName) {
|
||||
return fileName
|
||||
.replace(buildFolder, '')
|
||||
.replace(
|
||||
/\/?(.*)(\.[0-9a-f]+)(\.chunk)?(\.js|\.css)/,
|
||||
(match, p1, p2, p3, p4) => p1 + p4
|
||||
);
|
||||
}
|
||||
|
||||
// Input: 1024, 2048
|
||||
// Output: "(+1 KB)"
|
||||
function getDifferenceLabel(currentSize, previousSize) {
|
||||
var FIFTY_KILOBYTES = 1024 * 50;
|
||||
var difference = currentSize - previousSize;
|
||||
var fileSize = !Number.isNaN(difference) ? filesize(difference) : 0;
|
||||
if (difference >= FIFTY_KILOBYTES) {
|
||||
return chalk.red('+' + fileSize);
|
||||
} else if (difference < FIFTY_KILOBYTES && difference > 0) {
|
||||
return chalk.yellow('+' + fileSize);
|
||||
} else if (difference < 0) {
|
||||
return chalk.green(fileSize);
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function measureFileSizesBeforeBuild(buildFolder) {
|
||||
return new Promise(resolve => {
|
||||
recursive(buildFolder, (err, fileNames) => {
|
||||
var sizes;
|
||||
if (!err && fileNames) {
|
||||
sizes = fileNames
|
||||
.filter(fileName => /\.(js|css)$/.test(fileName))
|
||||
.reduce((memo, fileName) => {
|
||||
var contents = fs.readFileSync(fileName);
|
||||
var key = removeFileNameHash(buildFolder, fileName);
|
||||
memo[key] = gzipSize(contents);
|
||||
return memo;
|
||||
}, {});
|
||||
}
|
||||
resolve({
|
||||
root: buildFolder,
|
||||
sizes: sizes || {},
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
measureFileSizesBeforeBuild: measureFileSizesBeforeBuild,
|
||||
printFileSizesAfterBuild: printFileSizesAfterBuild,
|
||||
};
|
@ -1,44 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
// This Webpack plugin lets us interpolate custom variables into `index.html`.
|
||||
// Usage: `new InterpolateHtmlPlugin({ 'MY_VARIABLE': 42 })`
|
||||
// Then, you can use %MY_VARIABLE% in your `index.html`.
|
||||
|
||||
// It works in tandem with HtmlWebpackPlugin.
|
||||
// Learn more about creating plugins like this:
|
||||
// https://github.com/ampedandwired/html-webpack-plugin#events
|
||||
|
||||
'use strict';
|
||||
const escapeStringRegexp = require('escape-string-regexp');
|
||||
|
||||
class InterpolateHtmlPlugin {
|
||||
constructor(replacements) {
|
||||
this.replacements = replacements;
|
||||
}
|
||||
|
||||
apply(compiler) {
|
||||
compiler.plugin('compilation', compilation => {
|
||||
compilation.plugin(
|
||||
'html-webpack-plugin-before-html-processing',
|
||||
(data, callback) => {
|
||||
// Run HTML through a series of user-specified string replacements.
|
||||
Object.keys(this.replacements).forEach(key => {
|
||||
const value = this.replacements[key];
|
||||
data.html = data.html.replace(
|
||||
new RegExp('%' + escapeStringRegexp(key) + '%', 'g'),
|
||||
value
|
||||
);
|
||||
});
|
||||
callback(null, data);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InterpolateHtmlPlugin;
|
@ -1,81 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const chalk = require('chalk');
|
||||
const path = require('path');
|
||||
|
||||
class ModuleScopePlugin {
|
||||
constructor(appSrc, allowedFiles = []) {
|
||||
this.appSrc = appSrc;
|
||||
this.allowedFiles = new Set(allowedFiles);
|
||||
}
|
||||
|
||||
apply(resolver) {
|
||||
const { appSrc } = this;
|
||||
resolver.plugin('file', (request, callback) => {
|
||||
// Unknown issuer, probably webpack internals
|
||||
if (!request.context.issuer) {
|
||||
return callback();
|
||||
}
|
||||
if (
|
||||
// If this resolves to a node_module, we don't care what happens next
|
||||
request.descriptionFileRoot.indexOf('/node_modules/') !== -1 ||
|
||||
request.descriptionFileRoot.indexOf('\\node_modules\\') !== -1 ||
|
||||
// Make sure this request was manual
|
||||
!request.__innerRequest_request
|
||||
) {
|
||||
return callback();
|
||||
}
|
||||
// Resolve the issuer from our appSrc and make sure it's one of our files
|
||||
// Maybe an indexOf === 0 would be better?
|
||||
const relative = path.relative(appSrc, request.context.issuer);
|
||||
// If it's not in src/ or a subdirectory, not our request!
|
||||
if (relative.startsWith('../') || relative.startsWith('..\\')) {
|
||||
return callback();
|
||||
}
|
||||
const requestFullPath = path.resolve(
|
||||
path.dirname(request.context.issuer),
|
||||
request.__innerRequest_request
|
||||
);
|
||||
if (this.allowedFiles.has(requestFullPath)) {
|
||||
return callback();
|
||||
}
|
||||
// Find path from src to the requested file
|
||||
// Error if in a parent directory of src/
|
||||
const requestRelative = path.relative(appSrc, requestFullPath);
|
||||
if (
|
||||
requestRelative.startsWith('../') ||
|
||||
requestRelative.startsWith('..\\')
|
||||
) {
|
||||
callback(
|
||||
new Error(
|
||||
`You attempted to import ${chalk.cyan(
|
||||
request.__innerRequest_request
|
||||
)} which falls outside of the project ${chalk.cyan(
|
||||
'src/'
|
||||
)} directory. ` +
|
||||
`Relative imports outside of ${chalk.cyan(
|
||||
'src/'
|
||||
)} are not supported. ` +
|
||||
`You can either move it inside ${chalk.cyan(
|
||||
'src/'
|
||||
)}, or add a symlink to it from project's ${chalk.cyan(
|
||||
'node_modules/'
|
||||
)}.`
|
||||
),
|
||||
request
|
||||
);
|
||||
} else {
|
||||
callback();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ModuleScopePlugin;
|
@ -1,32 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
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;
|
@ -1,14 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
function clearConsole() {
|
||||
process.stdout.write(process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H');
|
||||
}
|
||||
|
||||
module.exports = clearConsole;
|
@ -1,12 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var crossSpawn = require('cross-spawn');
|
||||
|
||||
module.exports = crossSpawn;
|
@ -1,23 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const launchEditor = require('./launchEditor');
|
||||
const launchEditorEndpoint = require('./launchEditorEndpoint');
|
||||
|
||||
module.exports = function createLaunchEditorMiddleware() {
|
||||
return function launchEditorMiddleware(req, res, next) {
|
||||
if (req.url.startsWith(launchEditorEndpoint)) {
|
||||
const lineNumber = parseInt(req.query.lineNumber, 10) || 1;
|
||||
const colNumber = parseInt(req.query.colNumber, 10) || 1;
|
||||
launchEditor(req.query.fileName, lineNumber, colNumber);
|
||||
res.end();
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
};
|
||||
};
|
@ -1,92 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const chalk = require('chalk');
|
||||
const table = require('text-table');
|
||||
|
||||
function isError(message) {
|
||||
if (message.fatal || message.severity === 2) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function formatter(results) {
|
||||
let output = '\n';
|
||||
let hasErrors = false;
|
||||
let reportContainsErrorRuleIDs = false;
|
||||
|
||||
results.forEach(result => {
|
||||
let messages = result.messages;
|
||||
if (messages.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
messages = messages.map(message => {
|
||||
let messageType;
|
||||
if (isError(message)) {
|
||||
messageType = 'error';
|
||||
hasErrors = true;
|
||||
if (message.ruleId) {
|
||||
reportContainsErrorRuleIDs = true;
|
||||
}
|
||||
} else {
|
||||
messageType = 'warn';
|
||||
}
|
||||
|
||||
let line = message.line || 0;
|
||||
let position = chalk.bold('Line ' + line + ':');
|
||||
return [
|
||||
'',
|
||||
position,
|
||||
messageType,
|
||||
message.message.replace(/\.$/, ''),
|
||||
chalk.underline(message.ruleId || ''),
|
||||
];
|
||||
});
|
||||
|
||||
// if there are error messages, we want to show only errors
|
||||
if (hasErrors) {
|
||||
messages = messages.filter(m => m[2] === 'error');
|
||||
}
|
||||
|
||||
// add color to rule keywords
|
||||
messages.forEach(m => {
|
||||
m[4] = m[2] === 'error' ? chalk.red(m[4]) : chalk.yellow(m[4]);
|
||||
m.splice(2, 1);
|
||||
});
|
||||
|
||||
let outputTable = table(messages, {
|
||||
align: ['l', 'l', 'l'],
|
||||
stringLength(str) {
|
||||
return chalk.stripColor(str).length;
|
||||
},
|
||||
});
|
||||
|
||||
output += `${outputTable}\n\n`;
|
||||
});
|
||||
|
||||
if (reportContainsErrorRuleIDs) {
|
||||
// Unlike with warnings, we have to do it here.
|
||||
// We have similar code in react-scripts for warnings,
|
||||
// but warnings can appear in multiple files so we only
|
||||
// print it once at the end. For errors, however, we print
|
||||
// it here because we always show at most one error, and
|
||||
// we can only be sure it's an ESLint error before exiting
|
||||
// this function.
|
||||
output +=
|
||||
'Search for the ' +
|
||||
chalk.underline(chalk.red('keywords')) +
|
||||
' to learn more about each error.';
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
module.exports = formatter;
|
@ -1,136 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
// WARNING: this code is untranspiled and is used in browser too.
|
||||
// Please make sure any changes are in ES5 or contribute a Babel compile step.
|
||||
|
||||
// Some custom utilities to prettify Webpack output.
|
||||
// This is quite hacky and hopefully won't be needed when Webpack fixes this.
|
||||
// https://github.com/webpack/webpack/issues/2878
|
||||
|
||||
var chalk = require('chalk');
|
||||
var friendlySyntaxErrorLabel = 'Syntax error:';
|
||||
var path = require('path');
|
||||
|
||||
function isLikelyASyntaxError(message) {
|
||||
return message.indexOf(friendlySyntaxErrorLabel) !== -1;
|
||||
}
|
||||
|
||||
// VSCode problem matcher doesn't work with relative paths when they aren't workspace root
|
||||
function getAbsolutePath(p) {
|
||||
return path.resolve(__dirname, "..", p);
|
||||
}
|
||||
|
||||
// Cleans up webpack error messages.
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
function formatMessage(message, isError) {
|
||||
var lines = message.split('\n');
|
||||
|
||||
// Apparently react-dev-utils can't handle TS compiling errors well
|
||||
if (lines[0].startsWith('.')) return '';
|
||||
lines[0] = chalk.inverse(lines[0]);
|
||||
if (lines[0]) return lines.join('\n');
|
||||
|
||||
if (lines.length > 2 && lines[1] === '') {
|
||||
// Remove extra newline.
|
||||
lines.splice(1, 1);
|
||||
}
|
||||
|
||||
// Remove webpack-specific loader notation from filename.
|
||||
// Before:
|
||||
// ./~/css-loader!./~/postcss-loader!./src/App.css
|
||||
// After:
|
||||
// ./src/App.css
|
||||
if (lines[0].lastIndexOf('!') !== -1) {
|
||||
lines[0] = lines[0].substr(lines[0].lastIndexOf('!') + 1);
|
||||
}
|
||||
|
||||
lines = lines.filter(function(line) {
|
||||
// Webpack adds a list of entry points to warning messages:
|
||||
// @ ./src/index.js
|
||||
// @ multi react-scripts/~/react-dev-utils/webpackHotDevClient.js ...
|
||||
// It is misleading (and unrelated to the warnings) so we clean it up.
|
||||
// It is only useful for syntax errors but we have beautiful frames for them.
|
||||
return line.indexOf(' @ ') !== 0;
|
||||
});
|
||||
|
||||
// line #0 is filename
|
||||
// line #1 is the main error message
|
||||
if (!lines[0] || !lines[1]) {
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
// Cleans up verbose "module not found" messages for files and packages.
|
||||
if (lines[1].indexOf('Module not found: ') === 0) {
|
||||
lines = [
|
||||
lines[0],
|
||||
// Clean up message because "Module not found: " is descriptive enough.
|
||||
lines[1]
|
||||
.replace("Cannot resolve 'file' or 'directory' ", '')
|
||||
.replace('Cannot resolve module ', '')
|
||||
.replace('Error: ', '')
|
||||
.replace('[CaseSensitivePathsPlugin] ', ''),
|
||||
];
|
||||
}
|
||||
|
||||
// Cleans up syntax error messages.
|
||||
if (lines[1].indexOf('Module build failed: ') === 0) {
|
||||
lines[1] = lines[1].replace(
|
||||
'Module build failed: SyntaxError:',
|
||||
friendlySyntaxErrorLabel
|
||||
);
|
||||
}
|
||||
|
||||
// Clean up export errors.
|
||||
// TODO: we should really send a PR to Webpack for this.
|
||||
var exportError = /\s*(.+?)\s*(")?export '(.+?)' was not found in '(.+?)'/;
|
||||
if (lines[1].match(exportError)) {
|
||||
lines[1] = lines[1].replace(
|
||||
exportError,
|
||||
"$1 '$4' does not contain an export named '$3'."
|
||||
);
|
||||
}
|
||||
|
||||
lines[0] = chalk.inverse(getAbsolutePath(lines[0]));
|
||||
|
||||
// Reassemble the message.
|
||||
message = lines.join('\n');
|
||||
// Internal stacks are generally useless so we strip them... with the
|
||||
// exception of stacks containing `webpack:` because they're normally
|
||||
// from user code generated by WebPack. For more information see
|
||||
// https://github.com/facebookincubator/create-react-app/pull/1050
|
||||
message = message.replace(
|
||||
/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm,
|
||||
''
|
||||
); // at ... ...:x:y
|
||||
|
||||
return message.trim();
|
||||
}
|
||||
|
||||
function formatWebpackMessages(json) {
|
||||
var formattedErrors = json.errors.map(function(message) {
|
||||
return formatMessage(message, true);
|
||||
}).filter(s => !!s);
|
||||
var formattedWarnings = json.warnings.map(function(message) {
|
||||
return formatMessage(message, false);
|
||||
}).filter(s => !!s);
|
||||
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;
|
@ -1,82 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var chalk = require('chalk');
|
||||
var execSync = require('child_process').execSync;
|
||||
var path = require('path');
|
||||
|
||||
var execOptions = {
|
||||
encoding: 'utf8',
|
||||
stdio: [
|
||||
'pipe', // stdin (default)
|
||||
'pipe', // stdout (default)
|
||||
'ignore', //stderr
|
||||
],
|
||||
};
|
||||
|
||||
function isProcessAReactApp(processCommand) {
|
||||
return /^node .*react-scripts\/scripts\/start\.js\s?$/.test(processCommand);
|
||||
}
|
||||
|
||||
function getProcessIdOnPort(port) {
|
||||
return execSync('lsof -i:' + port + ' -P -t -sTCP:LISTEN', execOptions)
|
||||
.split('\n')[0]
|
||||
.trim();
|
||||
}
|
||||
|
||||
function getPackageNameInDirectory(directory) {
|
||||
var packagePath = path.join(directory.trim(), 'package.json');
|
||||
|
||||
try {
|
||||
return require(packagePath).name;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getProcessCommand(processId, processDirectory) {
|
||||
var command = execSync(
|
||||
'ps -o command -p ' + processId + ' | sed -n 2p',
|
||||
execOptions
|
||||
);
|
||||
|
||||
command = command.replace(/\n$/, '');
|
||||
|
||||
if (isProcessAReactApp(command)) {
|
||||
const packageName = getPackageNameInDirectory(processDirectory);
|
||||
return packageName ? packageName : command;
|
||||
} else {
|
||||
return command;
|
||||
}
|
||||
}
|
||||
|
||||
function getDirectoryOfProcessById(processId) {
|
||||
return execSync(
|
||||
'lsof -p ' + processId + ' | awk \'$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}\'',
|
||||
execOptions
|
||||
).trim();
|
||||
}
|
||||
|
||||
function getProcessForPort(port) {
|
||||
try {
|
||||
var processId = getProcessIdOnPort(port);
|
||||
var directory = getDirectoryOfProcessById(processId);
|
||||
var command = getProcessCommand(processId, directory);
|
||||
return (
|
||||
chalk.cyan(command) +
|
||||
chalk.grey(' (pid ' + processId + ')\n') +
|
||||
chalk.blue(' in ') +
|
||||
chalk.cyan(directory)
|
||||
);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = getProcessForPort;
|
@ -1,20 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const escape = require('escape-string-regexp');
|
||||
|
||||
module.exports = function ignoredFiles(appSrc) {
|
||||
return new RegExp(
|
||||
`^(?!${escape(
|
||||
path.normalize(appSrc + '/').replace(/[\\]+/g, '/')
|
||||
)}).+/node_modules/`,
|
||||
'g'
|
||||
);
|
||||
};
|
@ -1,12 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var inquirer = require('inquirer');
|
||||
|
||||
module.exports = inquirer;
|
File diff suppressed because one or more lines are too long
@ -1,10 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
// TODO: we might want to make this injectable to support DEV-time non-root URLs.
|
||||
module.exports = '/__open-stack-frame-in-editor';
|
@ -1,38 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports = function createNoopServiceWorkerMiddleware() {
|
||||
return function noopServiceWorkerMiddleware(req, res, next) {
|
||||
if (req.url === '/service-worker.js') {
|
||||
res.setHeader('Content-Type', 'text/javascript');
|
||||
res.send(
|
||||
`// This service worker file is effectively a 'no-op' that will reset any
|
||||
// previous service worker registered for the same host:port combination.
|
||||
// In the production build, this file is replaced with an actual service worker
|
||||
// file that will precache your site's local assets.
|
||||
// See https://github.com/facebookincubator/create-react-app/issues/2272#issuecomment-302832432
|
||||
|
||||
self.addEventListener('install', () => self.skipWaiting());
|
||||
|
||||
self.addEventListener('activate', () => {
|
||||
self.clients.matchAll({ type: 'window' }).then(windowClients => {
|
||||
for (let windowClient of windowClients) {
|
||||
// Force open pages to refresh, so that they have a chance to load the
|
||||
// fresh navigation response from the local dev server.
|
||||
windowClient.navigate(windowClient.url);
|
||||
}
|
||||
});
|
||||
});
|
||||
`
|
||||
);
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
};
|
||||
};
|
@ -1,126 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var chalk = require('chalk');
|
||||
var execSync = require('child_process').execSync;
|
||||
var spawn = require('cross-spawn');
|
||||
var opn = require('opn');
|
||||
|
||||
// https://github.com/sindresorhus/opn#app
|
||||
var OSX_CHROME = 'google chrome';
|
||||
|
||||
const Actions = Object.freeze({
|
||||
NONE: 0,
|
||||
BROWSER: 1,
|
||||
SCRIPT: 2,
|
||||
});
|
||||
|
||||
function getBrowserEnv() {
|
||||
// Attempt to honor this environment variable.
|
||||
// It is specific to the operating system.
|
||||
// See https://github.com/sindresorhus/opn#app for documentation.
|
||||
const value = process.env.BROWSER;
|
||||
let action;
|
||||
if (!value) {
|
||||
// Default.
|
||||
action = Actions.BROWSER;
|
||||
} else if (value.toLowerCase().endsWith('.js')) {
|
||||
action = Actions.SCRIPT;
|
||||
} else if (value.toLowerCase() === 'none') {
|
||||
action = Actions.NONE;
|
||||
} else {
|
||||
action = Actions.BROWSER;
|
||||
}
|
||||
return { action, value };
|
||||
}
|
||||
|
||||
function executeNodeScript(scriptPath, url) {
|
||||
const extraArgs = process.argv.slice(2);
|
||||
const child = spawn('node', [scriptPath, ...extraArgs, url], {
|
||||
stdio: 'inherit',
|
||||
});
|
||||
child.on('close', code => {
|
||||
if (code !== 0) {
|
||||
console.log();
|
||||
console.log(
|
||||
chalk.red(
|
||||
'The script specified as BROWSER environment variable failed.'
|
||||
)
|
||||
);
|
||||
console.log(chalk.cyan(scriptPath) + ' exited with code ' + code + '.');
|
||||
console.log();
|
||||
return;
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function startBrowserProcess(browser, url) {
|
||||
// If we're on OS X, the user hasn't specifically
|
||||
// requested a different browser, we can try opening
|
||||
// Chrome with AppleScript. This lets us reuse an
|
||||
// existing tab when possible instead of creating a new one.
|
||||
const shouldTryOpenChromeWithAppleScript =
|
||||
process.platform === 'darwin' &&
|
||||
(typeof browser !== 'string' || browser === OSX_CHROME);
|
||||
|
||||
if (shouldTryOpenChromeWithAppleScript) {
|
||||
try {
|
||||
// Try our best to reuse existing tab
|
||||
// on OS X Google Chrome with AppleScript
|
||||
execSync('ps cax | grep "Google Chrome"');
|
||||
execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', {
|
||||
cwd: __dirname,
|
||||
stdio: 'ignore',
|
||||
});
|
||||
return true;
|
||||
} catch (err) {
|
||||
// Ignore errors.
|
||||
}
|
||||
}
|
||||
|
||||
// Another special case: on OS X, check if BROWSER has been set to "open".
|
||||
// In this case, instead of passing `open` to `opn` (which won't work),
|
||||
// just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
|
||||
// https://github.com/facebookincubator/create-react-app/pull/1690#issuecomment-283518768
|
||||
if (process.platform === 'darwin' && browser === 'open') {
|
||||
browser = undefined;
|
||||
}
|
||||
|
||||
// Fallback to opn
|
||||
// (It will always open new tab)
|
||||
try {
|
||||
var options = { app: browser };
|
||||
opn(url, options).catch(() => {}); // Prevent `unhandledRejection` error.
|
||||
return true;
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the BROWSER evironment variable and decides what to do with it. Returns
|
||||
* true if it opened a browser or ran a node.js script, otherwise false.
|
||||
*/
|
||||
function openBrowser(url) {
|
||||
const { action, value } = getBrowserEnv();
|
||||
switch (action) {
|
||||
case Actions.NONE:
|
||||
// Special case: BROWSER="none" will prevent opening completely.
|
||||
return false;
|
||||
case Actions.SCRIPT:
|
||||
return executeNodeScript(value, url);
|
||||
case Actions.BROWSER:
|
||||
return startBrowserProcess(value, url);
|
||||
default:
|
||||
throw new Error('Not implemented.');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ()=> console.log('Skipped opening browser') || openBrowser;
|
@ -1,83 +0,0 @@
|
||||
(*
|
||||
Copyright (c) 2015-present, Facebook, Inc.
|
||||
|
||||
This source code is licensed under the MIT license found in the
|
||||
LICENSE file in the root directory of this source tree.
|
||||
*)
|
||||
|
||||
property targetTab: null
|
||||
property targetTabIndex: -1
|
||||
property targetWindow: null
|
||||
|
||||
on run argv
|
||||
set theURL to item 1 of argv
|
||||
|
||||
tell application "Chrome"
|
||||
|
||||
if (count every window) = 0 then
|
||||
make new window
|
||||
end if
|
||||
|
||||
-- 1: Looking for tab running debugger
|
||||
-- then, Reload debugging tab if found
|
||||
-- then return
|
||||
set found to my lookupTabWithUrl(theURL)
|
||||
if found then
|
||||
set targetWindow's active tab index to targetTabIndex
|
||||
tell targetTab to reload
|
||||
tell targetWindow to activate
|
||||
set index of targetWindow to 1
|
||||
return
|
||||
end if
|
||||
|
||||
-- 2: Looking for Empty tab
|
||||
-- In case debugging tab was not found
|
||||
-- We try to find an empty tab instead
|
||||
set found to my lookupTabWithUrl("chrome://newtab/")
|
||||
if found then
|
||||
set targetWindow's active tab index to targetTabIndex
|
||||
set URL of targetTab to theURL
|
||||
tell targetWindow to activate
|
||||
return
|
||||
end if
|
||||
|
||||
-- 3: Create new tab
|
||||
-- both debugging and empty tab were not found
|
||||
-- make a new tab with url
|
||||
tell window 1
|
||||
activate
|
||||
make new tab with properties {URL:theURL}
|
||||
end tell
|
||||
end tell
|
||||
end run
|
||||
|
||||
-- Function:
|
||||
-- Lookup tab with given url
|
||||
-- if found, store tab, index, and window in properties
|
||||
-- (properties were declared on top of file)
|
||||
on lookupTabWithUrl(lookupUrl)
|
||||
tell application "Chrome"
|
||||
-- Find a tab with the given url
|
||||
set found to false
|
||||
set theTabIndex to -1
|
||||
repeat with theWindow in every window
|
||||
set theTabIndex to 0
|
||||
repeat with theTab in every tab of theWindow
|
||||
set theTabIndex to theTabIndex + 1
|
||||
if (theTab's URL as string) contains lookupUrl then
|
||||
-- assign tab, tab index, and window to properties
|
||||
set targetTab to theTab
|
||||
set targetTabIndex to theTabIndex
|
||||
set targetWindow to theWindow
|
||||
set found to true
|
||||
exit repeat
|
||||
end if
|
||||
end repeat
|
||||
|
||||
if found then
|
||||
exit repeat
|
||||
end if
|
||||
end repeat
|
||||
end tell
|
||||
return found
|
||||
end lookupTabWithUrl
|
@ -1,71 +0,0 @@
|
||||
{
|
||||
"private": true,
|
||||
"bugs": {
|
||||
"url": "https://github.com/facebookincubator/create-react-app/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"address": "1.0.3",
|
||||
"babel-code-frame": "6.26.0",
|
||||
"chalk": "1.1.3",
|
||||
"cross-spawn": "5.1.0",
|
||||
"detect-port-alt": "1.1.6",
|
||||
"escape-string-regexp": "1.0.5",
|
||||
"filesize": "3.5.11",
|
||||
"global-modules": "1.0.0",
|
||||
"gzip-size": "3.0.0",
|
||||
"inquirer": "3.3.0",
|
||||
"is-root": "1.0.0",
|
||||
"opn": "5.2.0",
|
||||
"react-error-overlay": "^4.0.1",
|
||||
"recursive-readdir": "2.2.1",
|
||||
"shell-quote": "1.6.1",
|
||||
"sockjs-client": "1.1.5",
|
||||
"strip-ansi": "3.0.1",
|
||||
"text-table": "0.2.0"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Webpack utilities used by Create React App",
|
||||
"devDependencies": {
|
||||
"jest": "20.0.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"files": [
|
||||
"checkRequiredFiles.js",
|
||||
"clearConsole.js",
|
||||
"crashOverlay.js",
|
||||
"crossSpawn.js",
|
||||
"eslintFormatter.js",
|
||||
"errorOverlayMiddleware.js",
|
||||
"FileSizeReporter.js",
|
||||
"printBuildError.js",
|
||||
"formatWebpackMessages.js",
|
||||
"getProcessForPort.js",
|
||||
"ignoredFiles.js",
|
||||
"inquirer.js",
|
||||
"InterpolateHtmlPlugin.js",
|
||||
"launchEditor.js",
|
||||
"launchEditorEndpoint.js",
|
||||
"ModuleScopePlugin.js",
|
||||
"noopServiceWorkerMiddleware.js",
|
||||
"openBrowser.js",
|
||||
"openChrome.applescript",
|
||||
"printHostingInstructions.js",
|
||||
"WatchMissingNodeModulesPlugin.js",
|
||||
"WebpackDevServerUtils.js",
|
||||
"webpackHotDevClient.js"
|
||||
],
|
||||
"homepage": "https://github.com/facebookincubator/create-react-app#readme",
|
||||
"license": "MIT",
|
||||
"name": "react-dev-utils",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/facebookincubator/create-react-app.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "jest"
|
||||
},
|
||||
"version": "5.0.3"
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const chalk = require('chalk');
|
||||
|
||||
module.exports = function printBuildError(err) {
|
||||
const message = err != null && err.message;
|
||||
const stack = err != null && err.stack;
|
||||
|
||||
// Add more helpful message for UglifyJs error
|
||||
if (
|
||||
stack &&
|
||||
typeof message === 'string' &&
|
||||
message.indexOf('from UglifyJs') !== -1
|
||||
) {
|
||||
try {
|
||||
const matched = /(.+)\[(.+):(.+),(.+)\]\[.+\]/.exec(stack);
|
||||
if (!matched) {
|
||||
throw new Error('Using errors for control flow is bad.');
|
||||
}
|
||||
const problemPath = matched[2];
|
||||
const line = matched[3];
|
||||
const column = matched[4];
|
||||
console.log(
|
||||
'Failed to minify the code from this file: \n\n',
|
||||
chalk.yellow(
|
||||
`\t${problemPath}:${line}${column !== '0' ? ':' + column : ''}`
|
||||
),
|
||||
'\n'
|
||||
);
|
||||
} catch (ignored) {
|
||||
console.log('Failed to minify the bundle.', err);
|
||||
}
|
||||
console.log('Read more here: http://bit.ly/2tRViJ9');
|
||||
} else {
|
||||
console.log((message || err) + '\n');
|
||||
}
|
||||
console.log();
|
||||
};
|
@ -1,126 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const chalk = require('chalk');
|
||||
const url = require('url');
|
||||
const globalModules = require('global-modules');
|
||||
const fs = require('fs');
|
||||
|
||||
function printHostingInstructions(
|
||||
appPackage,
|
||||
publicUrl,
|
||||
publicPath,
|
||||
buildFolder,
|
||||
useYarn
|
||||
) {
|
||||
if (publicUrl && publicUrl.includes('.github.io/')) {
|
||||
// "homepage": "http://user.github.io/project"
|
||||
const publicPathname = url.parse(publicPath).pathname;
|
||||
const hasDeployScript = typeof appPackage.scripts.deploy !== 'undefined';
|
||||
printBaseMessage(buildFolder, publicPathname);
|
||||
|
||||
printDeployInstructions(publicUrl, hasDeployScript, useYarn);
|
||||
} else if (publicPath !== '/') {
|
||||
// "homepage": "http://mywebsite.com/project"
|
||||
printBaseMessage(buildFolder, publicPath);
|
||||
} else {
|
||||
// "homepage": "http://mywebsite.com"
|
||||
// or no homepage
|
||||
printBaseMessage(buildFolder, publicUrl);
|
||||
|
||||
printStaticServerInstructions(buildFolder, useYarn);
|
||||
}
|
||||
console.log();
|
||||
console.log('Find out more about deployment here:');
|
||||
console.log();
|
||||
console.log(` ${chalk.yellow('http://bit.ly/2vY88Kr')}`);
|
||||
console.log();
|
||||
}
|
||||
|
||||
function printBaseMessage(buildFolder, hostingLocation) {
|
||||
console.log(
|
||||
`The project was built assuming it is hosted at ${chalk.green(
|
||||
hostingLocation || 'the server root'
|
||||
)}.`
|
||||
);
|
||||
console.log(
|
||||
`You can control this with the ${chalk.green(
|
||||
'homepage'
|
||||
)} field in your ${chalk.cyan('package.json')}.`
|
||||
);
|
||||
|
||||
if (!hostingLocation) {
|
||||
console.log('For example, add this to build it for GitHub Pages:');
|
||||
console.log();
|
||||
|
||||
console.log(
|
||||
` ${chalk.green('"homepage"')} ${chalk.cyan(':')} ${chalk.green(
|
||||
'"http://myname.github.io/myapp"'
|
||||
)}${chalk.cyan(',')}`
|
||||
);
|
||||
}
|
||||
console.log();
|
||||
console.log(`The ${chalk.cyan(buildFolder)} folder is ready to be deployed.`);
|
||||
}
|
||||
|
||||
function printDeployInstructions(publicUrl, hasDeployScript, useYarn) {
|
||||
console.log(`To publish it at ${chalk.green(publicUrl)}, run:`);
|
||||
console.log();
|
||||
|
||||
// If script deploy has been added to package.json, skip the instructions
|
||||
if (!hasDeployScript) {
|
||||
if (useYarn) {
|
||||
console.log(` ${chalk.cyan('yarn')} add --dev gh-pages`);
|
||||
} else {
|
||||
console.log(` ${chalk.cyan('npm')} install --save-dev gh-pages`);
|
||||
}
|
||||
console.log();
|
||||
|
||||
console.log(
|
||||
`Add the following script in your ${chalk.cyan('package.json')}.`
|
||||
);
|
||||
console.log();
|
||||
|
||||
console.log(` ${chalk.dim('// ...')}`);
|
||||
console.log(` ${chalk.yellow('"scripts"')}: {`);
|
||||
console.log(` ${chalk.dim('// ...')}`);
|
||||
console.log(
|
||||
` ${chalk.yellow('"predeploy"')}: ${chalk.yellow(
|
||||
'"npm run build",'
|
||||
)}`
|
||||
);
|
||||
console.log(
|
||||
` ${chalk.yellow('"deploy"')}: ${chalk.yellow(
|
||||
'"gh-pages -d build"'
|
||||
)}`
|
||||
);
|
||||
console.log(' }');
|
||||
console.log();
|
||||
|
||||
console.log('Then run:');
|
||||
console.log();
|
||||
}
|
||||
console.log(` ${chalk.cyan(useYarn ? 'yarn' : 'npm')} run deploy`);
|
||||
}
|
||||
|
||||
function printStaticServerInstructions(buildFolder, useYarn) {
|
||||
console.log('You may serve it with a static server:');
|
||||
console.log();
|
||||
|
||||
if (!fs.existsSync(`${globalModules}/serve`)) {
|
||||
if (useYarn) {
|
||||
console.log(` ${chalk.cyan('yarn')} global add serve`);
|
||||
} else {
|
||||
console.log(` ${chalk.cyan('npm')} install -g serve`);
|
||||
}
|
||||
}
|
||||
console.log(` ${chalk.cyan('serve')} -s ${buildFolder}`);
|
||||
}
|
||||
|
||||
module.exports = printHostingInstructions;
|
@ -1,281 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
// This alternative WebpackDevServer combines the functionality of:
|
||||
// https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
|
||||
// https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js
|
||||
|
||||
// It only supports their simplest configuration (hot updates on same server).
|
||||
// It makes some opinionated choices on top, like adding a syntax error overlay
|
||||
// that looks similar to our console output. The error overlay is inspired by:
|
||||
// https://github.com/glenjamin/webpack-hot-middleware
|
||||
|
||||
var SockJS = require('sockjs-client');
|
||||
var stripAnsi = require('strip-ansi');
|
||||
var url = require('url');
|
||||
var launchEditorEndpoint = require('./launchEditorEndpoint');
|
||||
var formatWebpackMessages = require('./formatWebpackMessages');
|
||||
var ErrorOverlay = require('react-error-overlay');
|
||||
|
||||
ErrorOverlay.setEditorHandler(function editorHandler(errorLocation) {
|
||||
// Keep this sync with errorOverlayMiddleware.js
|
||||
fetch(
|
||||
launchEditorEndpoint +
|
||||
'?fileName=' +
|
||||
window.encodeURIComponent(errorLocation.fileName) +
|
||||
'&lineNumber=' +
|
||||
window.encodeURIComponent(errorLocation.lineNumber || 1) +
|
||||
'&colNumber=' +
|
||||
window.encodeURIComponent(errorLocation.colNumber || 1)
|
||||
);
|
||||
});
|
||||
|
||||
// We need to keep track of if there has been a runtime error.
|
||||
// Essentially, we cannot guarantee application state was not corrupted by the
|
||||
// runtime error. To prevent confusing behavior, we forcibly reload the entire
|
||||
// application. This is handled below when we are notified of a compile (code
|
||||
// change).
|
||||
// See https://github.com/facebookincubator/create-react-app/issues/3096
|
||||
var hadRuntimeError = false;
|
||||
ErrorOverlay.startReportingRuntimeErrors({
|
||||
onError: function() {
|
||||
hadRuntimeError = true;
|
||||
},
|
||||
filename: '/static/js/bundle.js',
|
||||
});
|
||||
|
||||
if (module.hot && typeof module.hot.dispose === 'function') {
|
||||
module.hot.dispose(function() {
|
||||
// TODO: why do we need this?
|
||||
ErrorOverlay.stopReportingRuntimeErrors();
|
||||
});
|
||||
}
|
||||
|
||||
// CHANGED THIS CUZ VSCODE
|
||||
const LOCATION = {
|
||||
protocol: 'http',
|
||||
hostname: 'localhost',
|
||||
port: 3000,
|
||||
}
|
||||
|
||||
// Connect to WebpackDevServer via a socket.
|
||||
var connection = new SockJS(
|
||||
url.format({
|
||||
protocol: LOCATION.protocol,
|
||||
hostname: LOCATION.hostname,
|
||||
port: LOCATION.port,
|
||||
// Hardcoded in WebpackDevServer
|
||||
pathname: '/sockjs-node',
|
||||
})
|
||||
);
|
||||
|
||||
// Unlike WebpackDevServer client, we won't try to reconnect
|
||||
// to avoid spamming the console. Disconnect usually happens
|
||||
// when developer stops the server.
|
||||
connection.onclose = function() {
|
||||
if (typeof console !== 'undefined' && typeof console.info === 'function') {
|
||||
console.info(
|
||||
'The development server has disconnected.\nRefresh the page if necessary.'
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Remember some state related to hot module replacement.
|
||||
var isFirstCompilation = true;
|
||||
var mostRecentCompilationHash = null;
|
||||
var hasCompileErrors = false;
|
||||
|
||||
function clearOutdatedErrors() {
|
||||
// Clean up outdated compile errors, if any.
|
||||
if (typeof console !== 'undefined' && typeof console.clear === 'function') {
|
||||
if (hasCompileErrors) {
|
||||
console.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Successful compilation.
|
||||
function handleSuccess() {
|
||||
clearOutdatedErrors();
|
||||
|
||||
var isHotUpdate = !isFirstCompilation;
|
||||
isFirstCompilation = false;
|
||||
hasCompileErrors = false;
|
||||
|
||||
// Attempt to apply hot updates or reload.
|
||||
if (isHotUpdate) {
|
||||
tryApplyUpdates(function onHotUpdateSuccess() {
|
||||
// Only dismiss it when we're sure it's a hot update.
|
||||
// Otherwise it would flicker right before the reload.
|
||||
ErrorOverlay.dismissBuildError();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Compilation with warnings (e.g. ESLint).
|
||||
function handleWarnings(warnings) {
|
||||
clearOutdatedErrors();
|
||||
|
||||
var isHotUpdate = !isFirstCompilation;
|
||||
isFirstCompilation = false;
|
||||
hasCompileErrors = false;
|
||||
|
||||
function printWarnings() {
|
||||
// Print warnings to the console.
|
||||
var formatted = formatWebpackMessages({
|
||||
warnings: warnings,
|
||||
errors: [],
|
||||
});
|
||||
|
||||
if (typeof console !== 'undefined' && typeof console.warn === 'function') {
|
||||
for (var i = 0; i < formatted.warnings.length; i++) {
|
||||
if (i === 5) {
|
||||
console.warn(
|
||||
'There were more warnings in other files.\n' +
|
||||
'You can find a complete log in the terminal.'
|
||||
);
|
||||
break;
|
||||
}
|
||||
console.warn(stripAnsi(formatted.warnings[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Attempt to apply hot updates or reload.
|
||||
if (isHotUpdate) {
|
||||
tryApplyUpdates(function onSuccessfulHotUpdate() {
|
||||
// Only print warnings if we aren't refreshing the page.
|
||||
// Otherwise they'll disappear right away anyway.
|
||||
printWarnings();
|
||||
// Only dismiss it when we're sure it's a hot update.
|
||||
// Otherwise it would flicker right before the reload.
|
||||
ErrorOverlay.dismissBuildError();
|
||||
});
|
||||
} else {
|
||||
// Print initial warnings immediately.
|
||||
printWarnings();
|
||||
}
|
||||
}
|
||||
|
||||
// Compilation with errors (e.g. syntax error or missing modules).
|
||||
function handleErrors(errors) {
|
||||
clearOutdatedErrors();
|
||||
|
||||
isFirstCompilation = false;
|
||||
hasCompileErrors = true;
|
||||
|
||||
// "Massage" webpack messages.
|
||||
var formatted = formatWebpackMessages({
|
||||
errors: errors,
|
||||
warnings: [],
|
||||
});
|
||||
|
||||
// Only show the first error.
|
||||
ErrorOverlay.reportBuildError(formatted.errors[0]);
|
||||
|
||||
// Also log them to the console.
|
||||
if (typeof console !== 'undefined' && typeof console.error === 'function') {
|
||||
for (var i = 0; i < formatted.errors.length; i++) {
|
||||
console.error(stripAnsi(formatted.errors[i]));
|
||||
}
|
||||
}
|
||||
|
||||
// Do not attempt to reload now.
|
||||
// We will reload on next success instead.
|
||||
}
|
||||
|
||||
// There is a newer version of the code available.
|
||||
function handleAvailableHash(hash) {
|
||||
// Update last known compilation hash.
|
||||
mostRecentCompilationHash = hash;
|
||||
}
|
||||
|
||||
// Handle messages from the server.
|
||||
connection.onmessage = function(e) {
|
||||
var message = JSON.parse(e.data);
|
||||
switch (message.type) {
|
||||
case 'hash':
|
||||
handleAvailableHash(message.data);
|
||||
break;
|
||||
case 'still-ok':
|
||||
case 'ok':
|
||||
handleSuccess();
|
||||
break;
|
||||
case 'content-changed':
|
||||
// Triggered when a file from `contentBase` changed.
|
||||
window.location.reload();
|
||||
break;
|
||||
case 'warnings':
|
||||
handleWarnings(message.data);
|
||||
break;
|
||||
case 'errors':
|
||||
handleErrors(message.data);
|
||||
break;
|
||||
default:
|
||||
// Do nothing.
|
||||
}
|
||||
};
|
||||
|
||||
// Is there a newer version of this code available?
|
||||
function isUpdateAvailable() {
|
||||
/* globals __webpack_hash__ */
|
||||
// __webpack_hash__ is the hash of the current compilation.
|
||||
// It's a global variable injected by Webpack.
|
||||
return mostRecentCompilationHash !== __webpack_hash__;
|
||||
}
|
||||
|
||||
// Webpack disallows updates in other states.
|
||||
function canApplyUpdates() {
|
||||
return module.hot.status() === 'idle';
|
||||
}
|
||||
|
||||
// Attempt to update code on the fly, fall back to a hard reload.
|
||||
function tryApplyUpdates(onHotUpdateSuccess) {
|
||||
if (!module.hot) {
|
||||
// HotModuleReplacementPlugin is not in Webpack configuration.
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isUpdateAvailable() || !canApplyUpdates()) {
|
||||
return;
|
||||
}
|
||||
|
||||
function handleApplyUpdates(err, updatedModules) {
|
||||
if (err || !updatedModules || hadRuntimeError) {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof onHotUpdateSuccess === 'function') {
|
||||
// Maybe we want to do something.
|
||||
onHotUpdateSuccess();
|
||||
}
|
||||
|
||||
if (isUpdateAvailable()) {
|
||||
// While we were updating, there was a new update! Do it again.
|
||||
tryApplyUpdates();
|
||||
}
|
||||
}
|
||||
|
||||
// https://webpack.github.io/docs/hot-module-replacement.html#check
|
||||
var result = module.hot.check(/* autoApply */ true, handleApplyUpdates);
|
||||
|
||||
// // Webpack 2 returns a Promise instead of invoking a callback
|
||||
if (result && result.then) {
|
||||
result.then(
|
||||
function(updatedModules) {
|
||||
handleApplyUpdates(null, updatedModules);
|
||||
},
|
||||
function(err) {
|
||||
handleApplyUpdates(err, null);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
Loading…
Reference in new issue