Reformat source code with Prettier 1.5.2

This commit is contained in:
Dan Abramov
2017-06-28 16:23:16 +01:00
parent 29c8733ec4
commit a171d93064
49 changed files with 420 additions and 270 deletions

View File

@@ -74,10 +74,14 @@ const program = new commander.Command(packageJson.name)
);
console.log(` - a specific npm version: ${chalk.green('0.8.2')}`);
console.log(
` - a custom fork published on npm: ${chalk.green('my-react-scripts')}`
` - a custom fork published on npm: ${chalk.green(
'my-react-scripts'
)}`
);
console.log(
` - a .tgz archive: ${chalk.green('https://mysite.com/my-react-scripts-0.8.2.tgz')}`
` - a .tgz archive: ${chalk.green(
'https://mysite.com/my-react-scripts-0.8.2.tgz'
)}`
);
console.log(
` It is not needed unless you specifically want to use a fork.`
@@ -87,7 +91,9 @@ const program = new commander.Command(packageJson.name)
` If you have any problems, do not hesitate to file an issue:`
);
console.log(
` ${chalk.cyan('https://github.com/facebookincubator/create-react-app/issues/new')}`
` ${chalk.cyan(
'https://github.com/facebookincubator/create-react-app/issues/new'
)}`
);
console.log();
})
@@ -258,15 +264,19 @@ function run(
console.log('Installing packages. This might take a couple of minutes.');
getPackageName(packageToInstall)
.then(packageName => checkIfOnline(useYarn).then(isOnline => ({
isOnline: isOnline,
packageName: packageName,
})))
.then(packageName =>
checkIfOnline(useYarn).then(isOnline => ({
isOnline: isOnline,
packageName: packageName,
}))
)
.then(info => {
const isOnline = info.isOnline;
const packageName = info.packageName;
console.log(
`Installing ${chalk.cyan('react')}, ${chalk.cyan('react-dom')}, and ${chalk.cyan(packageName)}...`
`Installing ${chalk.cyan('react')}, ${chalk.cyan(
'react-dom'
)}, and ${chalk.cyan(packageName)}...`
);
console.log();
@@ -334,7 +344,9 @@ function run(
if (!remainingFiles.length) {
// Delete target folder if empty
console.log(
`Deleting ${chalk.cyan(`${appName} /`)} from ${chalk.cyan(path.resolve(root, '..'))}`
`Deleting ${chalk.cyan(`${appName} /`)} from ${chalk.cyan(
path.resolve(root, '..')
)}`
);
process.chdir(path.resolve(root, '..'));
fs.removeSync(path.join(root));
@@ -422,7 +434,9 @@ function getPackageName(installPackage) {
/^.+\/(.+?)(?:-\d+.+)?\.tgz$/
)[1];
console.log(
`Based on the filename, assuming it is "${chalk.cyan(assumedProjectName)}"`
`Based on the filename, assuming it is "${chalk.cyan(
assumedProjectName
)}"`
);
return Promise.resolve(assumedProjectName);
});
@@ -485,7 +499,9 @@ function checkAppName(appName) {
const validationResult = validateProjectName(appName);
if (!validationResult.validForNewPackages) {
console.error(
`Could not create a project called ${chalk.red(`"${appName}"`)} because of npm naming restrictions:`
`Could not create a project called ${chalk.red(
`"${appName}"`
)} because of npm naming restrictions:`
);
printValidationResults(validationResult.errors);
printValidationResults(validationResult.warnings);
@@ -497,7 +513,9 @@ function checkAppName(appName) {
if (dependencies.indexOf(appName) >= 0) {
console.error(
chalk.red(
`We cannot create a project called ${chalk.green(appName)} because a dependency with the same name exists.\n` +
`We cannot create a project called ${chalk.green(
appName
)} because a dependency with the same name exists.\n` +
`Due to the way npm works, the following names are not allowed:\n\n`
) +
chalk.cyan(dependencies.map(depName => ` ${depName}`).join('\n')) +
@@ -519,7 +537,9 @@ function makeCaretRange(dependencies, name) {
if (!semver.validRange(patchedVersion)) {
console.error(
`Unable to patch ${name} dependency version because version ${chalk.red(version)} will become invalid ${chalk.red(patchedVersion)}`
`Unable to patch ${name} dependency version because version ${chalk.red(
version
)} will become invalid ${chalk.red(patchedVersion)}`
);
patchedVersion = version;
}

View File

@@ -236,7 +236,8 @@ module.exports = {
{
object: 'System',
property: 'import',
message: 'Please use import() instead. More info: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#code-splitting',
message:
'Please use import() instead. More info: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#code-splitting',
},
],

View File

@@ -119,15 +119,12 @@ function measureFileSizesBeforeBuild(buildFolder) {
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;
},
{}
);
.reduce((memo, fileName) => {
var contents = fs.readFileSync(fileName);
var key = removeFileNameHash(buildFolder, fileName);
memo[key] = gzipSize(contents);
return memo;
}, {});
}
resolve({
root: buildFolder,

View File

@@ -37,10 +37,7 @@ class ModuleScopePlugin {
// 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('..\\')
) {
if (relative.startsWith('../') || relative.startsWith('..\\')) {
return callback();
}
// Find path from src to the requested file
@@ -58,9 +55,19 @@ class ModuleScopePlugin {
) {
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/')}.`
`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
);

View File

@@ -37,18 +37,20 @@ if (isSmokeTest) {
}
function prepareUrls(protocol, host, port) {
const formatUrl = hostname => url.format({
protocol,
hostname,
port,
pathname: '/',
});
const prettyPrintUrl = hostname => url.format({
protocol,
hostname,
port: chalk.bold(port),
pathname: '/',
});
const formatUrl = hostname =>
url.format({
protocol,
hostname,
port,
pathname: '/',
});
const prettyPrintUrl = hostname =>
url.format({
protocol,
hostname,
port: chalk.bold(port),
pathname: '/',
});
const isUnspecifiedHost = host === '0.0.0.0' || host === '::';
let prettyHost, lanUrlForConfig, lanUrlForTerminal;
@@ -317,9 +319,11 @@ function prepareProxy(proxy, appPublicFolder) {
// However API calls like `fetch()` wont generally accept text/html.
// If this heuristic doesnt work well for you, use a custom `proxy` object.
context: function(pathname, req) {
return mayProxy(pathname) &&
return (
mayProxy(pathname) &&
req.headers.accept &&
req.headers.accept.indexOf('text/html') === -1;
req.headers.accept.indexOf('text/html') === -1
);
},
onProxyReq: proxyReq => {
// Browers may send Origin headers even with same-origin
@@ -375,39 +379,40 @@ function prepareProxy(proxy, appPublicFolder) {
function choosePort(host, defaultPort) {
return detect(defaultPort, host).then(
port => new Promise(resolve => {
if (port === defaultPort) {
return resolve(port);
}
const message = process.platform !== 'win32' &&
defaultPort < 1024 &&
!isRoot()
? `Admin permissions are required to run a server on a port below 1024.`
: `Something is already running on port ${defaultPort}.`;
if (isInteractive) {
clearConsole();
const existingProcess = getProcessForPort(defaultPort);
const question = {
type: 'confirm',
name: 'shouldChangePort',
message: chalk.yellow(
message +
`${existingProcess ? ` Probably:\n ${existingProcess}` : ''}`
) + '\n\nWould you like to run the app on another port instead?',
default: true,
};
inquirer.prompt(question).then(answer => {
if (answer.shouldChangePort) {
resolve(port);
} else {
resolve(null);
}
});
} else {
console.log(chalk.red(message));
resolve(null);
}
}),
port =>
new Promise(resolve => {
if (port === defaultPort) {
return resolve(port);
}
const message =
process.platform !== 'win32' && defaultPort < 1024 && !isRoot()
? `Admin permissions are required to run a server on a port below 1024.`
: `Something is already running on port ${defaultPort}.`;
if (isInteractive) {
clearConsole();
const existingProcess = getProcessForPort(defaultPort);
const question = {
type: 'confirm',
name: 'shouldChangePort',
message:
chalk.yellow(
message +
`${existingProcess ? ` Probably:\n ${existingProcess}` : ''}`
) + '\n\nWould you like to run the app on another port instead?',
default: true,
};
inquirer.prompt(question).then(answer => {
if (answer.shouldChangePort) {
resolve(port);
} else {
resolve(null);
}
});
} else {
console.log(chalk.red(message));
resolve(null);
}
}),
err => {
throw new Error(
chalk.red(`Could not find an open port at ${chalk.bold(host)}.`) +

View File

@@ -69,7 +69,8 @@ function ansiHTML(txt) {
var open = false;
for (var index = 0; index < arr.length; ++index) {
var c = arr[index];
var content = c.content, fg = c.fg;
var content = c.content,
fg = c.fg;
var contentParts = content.split('\n');
for (var _index = 0; _index < contentParts.length; ++_index) {

View File

@@ -82,7 +82,8 @@ function formatter(results) {
// 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 ' +
output +=
'Search for the ' +
chalk.underline(chalk.red('keywords')) +
' to learn more about each error.';
}

View File

@@ -30,10 +30,13 @@ function isTerminalEditor(editor) {
// of the app every time
const COMMON_EDITORS_OSX = {
'/Applications/Atom.app/Contents/MacOS/Atom': 'atom',
'/Applications/Atom Beta.app/Contents/MacOS/Atom Beta': '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
'/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':
'/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
'/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets',
'/Applications/Sublime Text.app/Contents/MacOS/Sublime Text': '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
'/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2': '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
'/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':
'/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
'/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':
'/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
'/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',
};

View File

@@ -68,7 +68,8 @@ function startBrowserProcess(browser, url) {
// 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' &&
const shouldTryOpenChromeWithAppleScript =
process.platform === 'darwin' &&
(typeof browser !== 'string' || browser === OSX_CHROME);
if (shouldTryOpenChromeWithAppleScript) {

View File

@@ -23,10 +23,14 @@ function printHostingInstructions(
if (publicUrl && publicUrl.indexOf('.github.io/') !== -1) {
// "homepage": "http://user.github.io/project"
console.log(
`The project was built assuming it is hosted at ${chalk.green(publicPathname)}.`
`The project was built assuming it is hosted at ${chalk.green(
publicPathname
)}.`
);
console.log(
`You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`
`You can control this with the ${chalk.green(
'homepage'
)} field in your ${chalk.cyan('package.json')}.`
);
console.log();
console.log(`The ${chalk.cyan('build')} folder is ready to be deployed.`);
@@ -48,10 +52,14 @@ function printHostingInstructions(
console.log(` ${chalk.yellow('"scripts"')}: {`);
console.log(` ${chalk.dim('// ...')}`);
console.log(
` ${chalk.yellow('"predeploy"')}: ${chalk.yellow('"npm run build",')}`
` ${chalk.yellow('"predeploy"')}: ${chalk.yellow(
'"npm run build",'
)}`
);
console.log(
` ${chalk.yellow('"deploy"')}: ${chalk.yellow('"gh-pages -d build"')}`
` ${chalk.yellow('"deploy"')}: ${chalk.yellow(
'"gh-pages -d build"'
)}`
);
console.log(' }');
console.log();
@@ -63,10 +71,14 @@ function printHostingInstructions(
} else if (publicPath !== '/') {
// "homepage": "http://mywebsite.com/project"
console.log(
`The project was built assuming it is hosted at ${chalk.green(publicPath)}.`
`The project was built assuming it is hosted at ${chalk.green(
publicPath
)}.`
);
console.log(
`You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`
`You can control this with the ${chalk.green(
'homepage'
)} field in your ${chalk.cyan('package.json')}.`
);
console.log();
console.log(`The ${chalk.cyan('build')} folder is ready to be deployed.`);
@@ -75,10 +87,14 @@ function printHostingInstructions(
if (publicUrl) {
// "homepage": "http://mywebsite.com"
console.log(
`The project was built assuming it is hosted at ${chalk.green(publicUrl)}.`
`The project was built assuming it is hosted at ${chalk.green(
publicUrl
)}.`
);
console.log(
`You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`
`You can control this with the ${chalk.green(
'homepage'
)} field in your ${chalk.cyan('package.json')}.`
);
console.log();
} else {
@@ -87,12 +103,16 @@ function printHostingInstructions(
'The project was built assuming it is hosted at the server root.'
);
console.log(
`To override this, specify the ${chalk.green('homepage')} in your ${chalk.cyan('package.json')}.`
`To override this, specify the ${chalk.green(
'homepage'
)} in your ${chalk.cyan('package.json')}.`
);
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(',')}`
` ${chalk.green('"homepage"')} ${chalk.cyan(':')} ${chalk.green(
'"http://myname.github.io/myapp"'
)}${chalk.cyan(',')}`
);
console.log();
}

View File

@@ -81,14 +81,16 @@ function addOverlayDivTo(iframe) {
}
function overlayHeaderStyle() {
return 'font-size: 2em;' +
return (
'font-size: 2em;' +
'font-family: sans-serif;' +
'color: rgb(206, 17, 38);' +
'white-space: pre-wrap;' +
'margin: 0 2rem 0.75rem 0px;' +
'flex: 0 0 auto;' +
'max-height: 35%;' +
'overflow: auto;';
'overflow: auto;'
);
}
var overlayIframe = null;
@@ -127,7 +129,8 @@ function ensureOverlayDivExists(onOverlayDivReady) {
function showErrorOverlay(message) {
ensureOverlayDivExists(function onOverlayDivReady(overlayDiv) {
// TODO: unify this with our runtime overlay
overlayDiv.innerHTML = '<div style="' +
overlayDiv.innerHTML =
'<div style="' +
overlayHeaderStyle() +
'">Failed to compile</div>' +
'<pre style="' +

View File

@@ -14,7 +14,8 @@ import { resolve } from 'path';
test('basic error; 0 context', async () => {
expect.assertions(1);
const error = 'TypeError: document.body.missing is not a function\n at App.componentDidMount (http://localhost:3000/static/js/bundle.js:26122:21)\n at http://localhost:3000/static/js/bundle.js:30091:25\n at measureLifeCyclePerf (http://localhost:3000/static/js/bundle.js:29901:12)\n at http://localhost:3000/static/js/bundle.js:30090:11\n at CallbackQueue.notifyAll (http://localhost:3000/static/js/bundle.js:13256:22)\n at ReactReconcileTransaction.close (http://localhost:3000/static/js/bundle.js:35124:26)\n at ReactReconcileTransaction.closeAll (http://localhost:3000/static/js/bundle.js:7390:25)\n at ReactReconcileTransaction.perform (http://localhost:3000/static/js/bundle.js:7337:16)\n at batchedMountComponentIntoNode (http://localhost:3000/static/js/bundle.js:14204:15)\n at ReactDefaultBatchingStrategyTransaction.perform (http://localhost:3000/static/js/bundle.js:7324:20)\n at Object.batchedUpdates (http://localhost:3000/static/js/bundle.js:33900:26)\n at Object.batchedUpdates (http://localhost:3000/static/js/bundle.js:2181:27)\n at Object._renderNewRootComponent (http://localhost:3000/static/js/bundle.js:14398:18)\n at Object._renderSubtreeIntoContainer (http://localhost:3000/static/js/bundle.js:14479:32)\n at Object.render (http://localhost:3000/static/js/bundle.js:14500:23)\n at Object.friendlySyntaxErrorLabel (http://localhost:3000/static/js/bundle.js:17287:20)\n at __webpack_require__ (http://localhost:3000/static/js/bundle.js:660:30)\n at fn (http://localhost:3000/static/js/bundle.js:84:20)\n at Object.<anonymous> (http://localhost:3000/static/js/bundle.js:41219:18)\n at __webpack_require__ (http://localhost:3000/static/js/bundle.js:660:30)\n at validateFormat (http://localhost:3000/static/js/bundle.js:709:39)\n at http://localhost:3000/static/js/bundle.js:712:10';
const error =
'TypeError: document.body.missing is not a function\n at App.componentDidMount (http://localhost:3000/static/js/bundle.js:26122:21)\n at http://localhost:3000/static/js/bundle.js:30091:25\n at measureLifeCyclePerf (http://localhost:3000/static/js/bundle.js:29901:12)\n at http://localhost:3000/static/js/bundle.js:30090:11\n at CallbackQueue.notifyAll (http://localhost:3000/static/js/bundle.js:13256:22)\n at ReactReconcileTransaction.close (http://localhost:3000/static/js/bundle.js:35124:26)\n at ReactReconcileTransaction.closeAll (http://localhost:3000/static/js/bundle.js:7390:25)\n at ReactReconcileTransaction.perform (http://localhost:3000/static/js/bundle.js:7337:16)\n at batchedMountComponentIntoNode (http://localhost:3000/static/js/bundle.js:14204:15)\n at ReactDefaultBatchingStrategyTransaction.perform (http://localhost:3000/static/js/bundle.js:7324:20)\n at Object.batchedUpdates (http://localhost:3000/static/js/bundle.js:33900:26)\n at Object.batchedUpdates (http://localhost:3000/static/js/bundle.js:2181:27)\n at Object._renderNewRootComponent (http://localhost:3000/static/js/bundle.js:14398:18)\n at Object._renderSubtreeIntoContainer (http://localhost:3000/static/js/bundle.js:14479:32)\n at Object.render (http://localhost:3000/static/js/bundle.js:14500:23)\n at Object.friendlySyntaxErrorLabel (http://localhost:3000/static/js/bundle.js:17287:20)\n at __webpack_require__ (http://localhost:3000/static/js/bundle.js:660:30)\n at fn (http://localhost:3000/static/js/bundle.js:84:20)\n at Object.<anonymous> (http://localhost:3000/static/js/bundle.js:41219:18)\n at __webpack_require__ (http://localhost:3000/static/js/bundle.js:660:30)\n at validateFormat (http://localhost:3000/static/js/bundle.js:709:39)\n at http://localhost:3000/static/js/bundle.js:712:10';
fetch.mockResponseOnce(
fs
@@ -38,7 +39,8 @@ test('basic error; 0 context', async () => {
test('default context (3)', async () => {
expect.assertions(1);
const error = 'TypeError: document.body.missing is not a function\n at App.componentDidMount (http://localhost:3000/static/js/bundle.js:26122:21)';
const error =
'TypeError: document.body.missing is not a function\n at App.componentDidMount (http://localhost:3000/static/js/bundle.js:26122:21)';
fetch.mockResponseOnce(
fs
@@ -62,7 +64,8 @@ test('default context (3)', async () => {
test('bad comes back same', async () => {
expect.assertions(2);
const error = 'TypeError: document.body.missing is not a function\n at App.componentDidMount (A:1:2)';
const error =
'TypeError: document.body.missing is not a function\n at App.componentDidMount (A:1:2)';
const orig = parse(error);
expect(orig).toEqual([
{

View File

@@ -242,8 +242,8 @@ function createFrame(
let needsHidden = false;
const isInternalUrl = isInternalFile(sourceFileName, fileName);
const isThrownIntentionally = !isBultinErrorName(errorName);
const shouldCollapse = isInternalUrl &&
(isThrownIntentionally || omits.hasReachedAppCode);
const shouldCollapse =
isInternalUrl && (isThrownIntentionally || omits.hasReachedAppCode);
if (!isInternalUrl) {
omits.hasReachedAppCode = true;
@@ -281,9 +281,8 @@ function createFrame(
let onSourceClick = null;
if (sourceFileName) {
// e.g. "/path-to-my-app/webpack/bootstrap eaddeb46b67d75e4dfc1"
const isInternalWebpackBootstrapCode = sourceFileName
.trim()
.indexOf(' ') !== -1;
const isInternalWebpackBootstrapCode =
sourceFileName.trim().indexOf(' ') !== -1;
if (!isInternalWebpackBootstrapCode) {
onSourceClick = () => {
// Keep this in sync with react-error-overlay/middleware.js
@@ -312,7 +311,10 @@ function createFrame(
let hasSource = false;
if (!shouldCollapse) {
if (
compiled && scriptLines && scriptLines.length !== 0 && lineNumber != null
compiled &&
scriptLines &&
scriptLines.length !== 0 &&
lineNumber != null
) {
elem.appendChild(
createCode(

View File

@@ -60,9 +60,8 @@ function createOverlay(
applyStyles(header, headerStyle);
// Make message prettier
let finalMessage = message.match(/^\w*:/) || !name
? message
: name + ': ' + message;
let finalMessage =
message.match(/^\w*:/) || !name ? message : name + ': ' + message;
finalMessage = finalMessage
// TODO: maybe remove this prefix from fbjs?

View File

@@ -9,13 +9,15 @@
/* @flow */
function isInternalFile(sourceFileName: ?string, fileName: ?string) {
return sourceFileName == null ||
return (
sourceFileName == null ||
sourceFileName === '' ||
sourceFileName.indexOf('/~/') !== -1 ||
sourceFileName.indexOf('/node_modules/') !== -1 ||
sourceFileName.trim().indexOf(' ') !== -1 ||
fileName == null ||
fileName === '';
fileName === ''
);
}
export { isInternalFile };

View File

@@ -15,7 +15,8 @@ import path from 'path';
function count(search: string, string: string): number {
// Count starts at -1 becuse a do-while loop always runs at least once
let count = -1, index = -1;
let count = -1,
index = -1;
do {
// First call or the while case evaluated true, meaning we have to make
// count 0 or we found a character

View File

@@ -88,13 +88,10 @@ function getClientEnvironment(publicUrl) {
);
// Stringify all values so we can feed into Webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce(
(env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
},
{}
),
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };

View File

@@ -43,8 +43,8 @@ const getPublicUrl = appPackageJson =>
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson);
const servedUrl = envPublicUrl ||
(publicUrl ? url.parse(publicUrl).pathname : '/');
const servedUrl =
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
return ensureSlash(servedUrl, true);
}
@@ -89,7 +89,8 @@ module.exports = {
const ownPackageJson = require('../package.json');
const reactScriptsPath = resolveApp(`node_modules/${ownPackageJson.name}`);
const reactScriptsLinked = fs.existsSync(reactScriptsPath) &&
const reactScriptsLinked =
fs.existsSync(reactScriptsPath) &&
fs.lstatSync(reactScriptsPath).isSymbolicLink();
// config before publish: we're in ./packages/react-scripts/config/

View File

@@ -36,8 +36,8 @@ module.exports = function(proxy, allowedHost) {
// So we will disable the host check normally, but enable it if you have
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
disableHostCheck: !proxy ||
process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
disableHostCheck:
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
// Enable gzip compression of generated files.
compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful.

View File

@@ -50,9 +50,10 @@ describe('Integration', () => {
it('PUBLIC_URL', async () => {
const doc = await initDOM('public-url');
const prefix = process.env.NODE_ENV === 'development'
? ''
: 'http://www.example.org/spa';
const prefix =
process.env.NODE_ENV === 'development'
? ''
: 'http://www.example.org/spa';
expect(doc.getElementById('feature-public-url').textContent).to.equal(
`${prefix}.`
);

View File

@@ -38,13 +38,14 @@ if (process.env.E2E_FILE) {
)
);
} else if (process.env.E2E_URL) {
getMarkup = () => new Promise(resolve => {
http.get(process.env.E2E_URL, res => {
let rawData = '';
res.on('data', chunk => rawData += chunk);
res.on('end', () => resolve(rawData));
getMarkup = () =>
new Promise(resolve => {
http.get(process.env.E2E_URL, res => {
let rawData = '';
res.on('data', chunk => (rawData += chunk));
res.on('end', () => resolve(rawData));
});
});
});
resourceLoader = (resource, callback) => resource.defaultFetch(callback);
} else {
@@ -58,21 +59,22 @@ if (process.env.E2E_FILE) {
);
}
export default feature => new Promise(async resolve => {
const markup = await getMarkup();
const host = process.env.E2E_URL || 'http://www.example.org/spa:3000';
const doc = jsdom.jsdom(markup, {
features: {
FetchExternalResources: ['script', 'css'],
ProcessExternalResources: ['script'],
},
created: (_, win) =>
win.addEventListener('ReactFeatureDidMount', () => resolve(doc), true),
deferClose: true,
resourceLoader,
url: `${host}#${feature}`,
virtualConsole: jsdom.createVirtualConsole().sendTo(console),
});
export default feature =>
new Promise(async resolve => {
const markup = await getMarkup();
const host = process.env.E2E_URL || 'http://www.example.org/spa:3000';
const doc = jsdom.jsdom(markup, {
features: {
FetchExternalResources: ['script', 'css'],
ProcessExternalResources: ['script'],
},
created: (_, win) =>
win.addEventListener('ReactFeatureDidMount', () => resolve(doc), true),
deferClose: true,
resourceLoader,
url: `${host}#${feature}`,
virtualConsole: jsdom.createVirtualConsole().sendTo(console),
});
doc.close();
});
doc.close();
});

View File

@@ -30,10 +30,7 @@ class BuiltEmitter extends Component {
}
render() {
const {
props: { feature },
handleReady,
} = this;
const { props: { feature }, handleReady } = this;
return (
<div>
{createElement(feature, {
@@ -57,114 +54,132 @@ class App extends Component {
const feature = window.location.hash.slice(1);
switch (feature) {
case 'array-destructuring':
import(
'./features/syntax/ArrayDestructuring'
).then(f => this.setFeature(f.default));
import('./features/syntax/ArrayDestructuring').then(f =>
this.setFeature(f.default)
);
break;
case 'array-spread':
import('./features/syntax/ArraySpread').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'async-await':
import('./features/syntax/AsyncAwait').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'class-properties':
import('./features/syntax/ClassProperties').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'computed-properties':
import(
'./features/syntax/ComputedProperties'
).then(f => this.setFeature(f.default));
import('./features/syntax/ComputedProperties').then(f =>
this.setFeature(f.default)
);
break;
case 'css-inclusion':
import('./features/webpack/CssInclusion').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'custom-interpolation':
import(
'./features/syntax/CustomInterpolation'
).then(f => this.setFeature(f.default));
import('./features/syntax/CustomInterpolation').then(f =>
this.setFeature(f.default)
);
break;
case 'default-parameters':
import('./features/syntax/DefaultParameters').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'destructuring-and-await':
import(
'./features/syntax/DestructuringAndAwait'
).then(f => this.setFeature(f.default));
import('./features/syntax/DestructuringAndAwait').then(f =>
this.setFeature(f.default)
);
break;
case 'file-env-variables':
import('./features/env/FileEnvVariables').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'generators':
import('./features/syntax/Generators').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'image-inclusion':
import('./features/webpack/ImageInclusion').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'json-inclusion':
import('./features/webpack/JsonInclusion').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'linked-modules':
import('./features/webpack/LinkedModules').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'node-path':
import('./features/env/NodePath').then(f => this.setFeature(f.default));
break;
case 'no-ext-inclusion':
import('./features/webpack/NoExtInclusion').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'object-destructuring':
import(
'./features/syntax/ObjectDestructuring'
).then(f => this.setFeature(f.default));
import('./features/syntax/ObjectDestructuring').then(f =>
this.setFeature(f.default)
);
break;
case 'object-spread':
import('./features/syntax/ObjectSpread').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'promises':
import('./features/syntax/Promises').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'public-url':
import('./features/env/PublicUrl').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'rest-and-default':
import('./features/syntax/RestAndDefault').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'rest-parameters':
import('./features/syntax/RestParameters').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'shell-env-variables':
import('./features/env/ShellEnvVariables').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'svg-inclusion':
import('./features/webpack/SvgInclusion').then(f =>
this.setFeature(f.default));
this.setFeature(f.default)
);
break;
case 'template-interpolation':
import(
'./features/syntax/TemplateInterpolation'
).then(f => this.setFeature(f.default));
import('./features/syntax/TemplateInterpolation').then(f =>
this.setFeature(f.default)
);
break;
case 'unknown-ext-inclusion':
import(
'./features/webpack/UnknownExtInclusion'
).then(f => this.setFeature(f.default));
import('./features/webpack/UnknownExtInclusion').then(f =>
this.setFeature(f.default)
);
break;
default:
throw new Error(`Missing feature "${feature}"`);

View File

@@ -9,7 +9,7 @@
import React from 'react';
export default () => (
export default () =>
<span>
<span id="feature-file-env-original-1">
{process.env.REACT_APP_ORIGINAL_1}
@@ -18,8 +18,10 @@ export default () => (
{process.env.REACT_APP_ORIGINAL_2}
</span>
<span id="feature-file-env">
{process.env.REACT_APP_DEVELOPMENT}{process.env.REACT_APP_PRODUCTION}
{process.env.REACT_APP_DEVELOPMENT}
{process.env.REACT_APP_PRODUCTION}
</span>
<span id="feature-file-env-x">{process.env.REACT_APP_X}</span>
</span>
);
<span id="feature-file-env-x">
{process.env.REACT_APP_X}
</span>
</span>;

View File

@@ -33,7 +33,11 @@ export default class extends Component {
render() {
return (
<div id="feature-node-path">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
{this.state.users.map(user =>
<div key={user.id}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -9,6 +9,7 @@
import React from 'react';
export default () => (
<span id="feature-public-url">{process.env.PUBLIC_URL}.</span>
);
export default () =>
<span id="feature-public-url">
{process.env.PUBLIC_URL}.
</span>;

View File

@@ -9,8 +9,7 @@
import React from 'react';
export default () => (
export default () =>
<span id="feature-shell-env-variables">
{process.env.REACT_APP_SHELL_ENV_MESSAGE}.
</span>
);
</span>;

View File

@@ -38,7 +38,11 @@ export default class extends Component {
<div id="feature-array-destructuring">
{this.state.users.map(user => {
const [id, name] = user;
return <div key={id}>{name}</div>;
return (
<div key={id}>
{name}
</div>
);
})}
</div>
);

View File

@@ -41,7 +41,11 @@ export default class extends Component {
render() {
return (
<div id="feature-array-spread">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
{this.state.users.map(user =>
<div key={user.id}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -41,7 +41,11 @@ export default class extends Component {
render() {
return (
<div id="feature-async-await">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
{this.state.users.map(user =>
<div key={user.id}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -29,7 +29,11 @@ export default class extends Component {
render() {
return (
<div id="feature-class-properties">
{this.users.map(user => <div key={user.id}>{user.name}</div>)}
{this.users.map(user =>
<div key={user.id}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -41,9 +41,11 @@ export default class extends Component {
render() {
return (
<div id="feature-computed-properties">
{this.state.users.map(user => (
<div key={user.id}>{user.user_name}</div>
))}
{this.state.users.map(user =>
<div key={user.id}>
{user.user_name}
</div>
)}
</div>
);
}

View File

@@ -53,9 +53,11 @@ export default class extends Component {
return (
<div id="feature-custom-interpolation">
{this.state.users.map(user => (
<div key={user.id} style={veryInlineStyle}>{user.name}</div>
))}
{this.state.users.map(user =>
<div key={user.id} style={veryInlineStyle}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -41,7 +41,11 @@ export default class extends Component {
render() {
return (
<div id="feature-default-parameters">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
{this.state.users.map(user =>
<div key={user.id}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -43,7 +43,11 @@ export default class extends Component {
render() {
return (
<div id="feature-destructuring-and-await">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
{this.state.users.map(user =>
<div key={user.id}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -43,7 +43,11 @@ export default class extends Component {
render() {
return (
<div id="feature-generators">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
{this.state.users.map(user =>
<div key={user.id}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -43,7 +43,11 @@ export default class extends Component {
<div id="feature-object-destructuring">
{this.state.users.map(user => {
const { id, name } = user;
return <div key={id}>{name}</div>;
return (
<div key={id}>
{name}
</div>
);
})}
</div>
);

View File

@@ -41,9 +41,11 @@ export default class extends Component {
render() {
return (
<div id="feature-object-spread">
{this.state.users.map(user => (
<div key={user.id}>{user.name}: {user.age}</div>
))}
{this.state.users.map(user =>
<div key={user.id}>
{user.name}: {user.age}
</div>
)}
</div>
);
}

View File

@@ -42,7 +42,11 @@ export default class extends Component {
render() {
return (
<div id="feature-promises">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
{this.state.users.map(user =>
<div key={user.id}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -41,7 +41,11 @@ export default class extends Component {
render() {
return (
<div id="feature-rest-and-default">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
{this.state.users.map(user =>
<div key={user.id}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -41,7 +41,11 @@ export default class extends Component {
render() {
return (
<div id="feature-rest-parameters">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
{this.state.users.map(user =>
<div key={user.id}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -41,7 +41,11 @@ export default class extends Component {
render() {
return (
<div id="feature-template-interpolation">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
{this.state.users.map(user =>
<div key={user.id}>
{user.name}
</div>
)}
</div>
);
}

View File

@@ -10,6 +10,5 @@
import React from 'react';
import tiniestCat from './assets/tiniest-cat.jpg';
export default () => (
<img id="feature-image-inclusion" src={tiniestCat} alt="tiniest cat" />
);
export default () =>
<img id="feature-image-inclusion" src={tiniestCat} alt="tiniest cat" />;

View File

@@ -10,4 +10,7 @@
import React from 'react';
import { abstract } from './assets/abstract.json';
export default () => <summary id="feature-json-inclusion">{abstract}</summary>;
export default () =>
<summary id="feature-json-inclusion">
{abstract}
</summary>;

View File

@@ -16,5 +16,9 @@ export default () => {
if (!test() || v !== '2.0.0') {
throw new Error('Functionality test did not pass.');
}
return <p id="feature-linked-modules">{v}</p>;
return (
<p id="feature-linked-modules">
{v}
</p>
);
};

View File

@@ -14,6 +14,7 @@ const text = aFileWithoutExt.includes('base64')
? atob(aFileWithoutExt.split('base64,')[1]).trim()
: aFileWithoutExt;
export default () => (
<a id="feature-no-ext-inclusion" href={text}>aFileWithoutExt</a>
);
export default () =>
<a id="feature-no-ext-inclusion" href={text}>
aFileWithoutExt
</a>;

View File

@@ -14,6 +14,7 @@ const text = aFileWithExtUnknown.includes('base64')
? atob(aFileWithExtUnknown.split('base64,')[1]).trim()
: aFileWithExtUnknown;
export default () => (
<a id="feature-unknown-ext-inclusion" href={text}>aFileWithExtUnknown</a>
);
export default () =>
<a id="feature-unknown-ext-inclusion" href={text}>
aFileWithExtUnknown
</a>;

View File

@@ -35,7 +35,8 @@ const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild;
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);

View File

@@ -85,19 +85,16 @@ inquirer
const folders = ['config', 'config/jest', 'scripts'];
// Make shallow array of files paths
const files = folders.reduce(
(files, folder) => {
return files.concat(
fs
.readdirSync(path.join(ownPath, folder))
// set full path
.map(file => path.join(ownPath, folder, file))
// omit dirs from file list
.filter(file => fs.lstatSync(file).isFile())
);
},
[]
);
const files = folders.reduce((files, folder) => {
return files.concat(
fs
.readdirSync(path.join(ownPath, folder))
// set full path
.map(file => path.join(ownPath, folder, file))
// omit dirs from file list
.filter(file => fs.lstatSync(file).isFile())
);
}, []);
// Ensure that the app folder is clean and we won't override any files
folders.forEach(verifyAbsent);
@@ -124,18 +121,19 @@ inquirer
if (content.match(/\/\/ @remove-file-on-eject/)) {
return;
}
content = content
// Remove dead code from .js files on eject
.replace(
/\/\/ @remove-on-eject-begin([\s\S]*?)\/\/ @remove-on-eject-end/mg,
''
)
// Remove dead code from .applescript files on eject
.replace(
/-- @remove-on-eject-begin([\s\S]*?)-- @remove-on-eject-end/mg,
''
)
.trim() + '\n';
content =
content
// Remove dead code from .js files on eject
.replace(
/\/\/ @remove-on-eject-begin([\s\S]*?)\/\/ @remove-on-eject-end/gm,
''
)
// Remove dead code from .applescript files on eject
.replace(
/-- @remove-on-eject-begin([\s\S]*?)-- @remove-on-eject-end/gm,
''
)
.trim() + '\n';
console.log(` Adding ${cyan(file.replace(ownPath, ''))} to the project`);
fs.writeFileSync(file.replace(ownPath, appPath), content);
});
@@ -187,7 +185,9 @@ inquirer
'node scripts/$1.js'
);
console.log(
` Replacing ${cyan(`"${binKey} ${key}"`)} with ${cyan(`"node scripts/${key}.js"`)}`
` Replacing ${cyan(`"${binKey} ${key}"`)} with ${cyan(
`"node scripts/${key}.js"`
)}`
);
});
});

View File

@@ -28,11 +28,8 @@ module.exports = function(
originalDirectory,
template
) {
const ownPackageName = require(path.join(
__dirname,
'..',
'package.json'
)).name;
const ownPackageName = require(path.join(__dirname, '..', 'package.json'))
.name;
const ownPath = path.join(appPath, 'node_modules', ownPackageName);
const appPackage = require(path.join(appPath, 'package.json'));
const useYarn = fs.existsSync(path.join(appPath, 'yarn.lock'));
@@ -192,6 +189,8 @@ module.exports = function(
function isReactInstalled(appPackage) {
const dependencies = appPackage.dependencies || {};
return typeof dependencies.react !== 'undefined' &&
typeof dependencies['react-dom'] !== 'undefined';
return (
typeof dependencies.react !== 'undefined' &&
typeof dependencies['react-dom'] !== 'undefined'
);
}