diff --git a/packages/create-react-app/createReactApp.js b/packages/create-react-app/createReactApp.js index ebeae5b41b0..7e51179b5ab 100755 --- a/packages/create-react-app/createReactApp.js +++ b/packages/create-react-app/createReactApp.js @@ -1,5 +1,3 @@ -#!/usr/bin/env node - /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. @@ -8,109 +6,68 @@ * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ - -// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// /!\ DO NOT MODIFY THIS FILE /!\ -// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// -// create-react-app is installed globally on people's computers. This means -// that it is extremely difficult to have them upgrade the version and -// because there's only one global version installed, it is very prone to -// breaking changes. -// -// The only job of create-react-app is to init the repository and then -// forward all the commands to the local version of create-react-app. -// -// If you need to add a new command, please add it to the scripts/ folder. -// -// The only reason to modify this file is to add more warnings and -// troubleshooting information for the `create-react-app` command. -// -// Do not make breaking changes! We absolutely don't want to have to -// tell people to update their global version of create-react-app. -// -// Also be careful with new language features. -// This file must work on Node 0.10+. -// -// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// /!\ DO NOT MODIFY THIS FILE /!\ -// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 'use strict'; -var chalk = require('chalk'); -var validateProjectName = require("validate-npm-package-name"); - -var currentNodeVersion = process.versions.node; -if (currentNodeVersion.split('.')[0] < 4) { - console.error( - chalk.red( - 'You are running Node ' + currentNodeVersion + '.\n' + - 'Create React App requires Node 4 or higher. \n' + - 'Please update your version of Node.' - ) - ); - process.exit(1); -} - -var commander = require('commander'); -var fs = require('fs-extra'); -var path = require('path'); -var execSync = require('child_process').execSync; -var spawn = require('cross-spawn'); -var semver = require('semver'); -var dns = require('dns'); -var tmp = require('tmp'); -var unpack = require('tar-pack').unpack; -var hyperquest = require('hyperquest'); - -var projectName; - -var program = commander +const validateProjectName = require("validate-npm-package-name"); +const chalk = require('chalk'); +const commander = require('commander'); +const fs = require('fs-extra'); +const path = require('path'); +const execSync = require('child_process').execSync; +const spawn = require('cross-spawn'); +const semver = require('semver'); +const dns = require('dns'); +const tmp = require('tmp'); +const unpack = require('tar-pack').unpack; +const hyperquest = require('hyperquest'); + +let projectName; + +const program = commander .version(require('./package.json').version) .arguments('') - .usage(chalk.green('') + ' [options]') - .action(function (name) { + .usage(`${chalk.green('')} [options]`) + .action(name => { projectName = name; }) .option('--verbose', 'print additional logs') .option('--scripts-version ', 'use a non-standard version of react-scripts') .allowUnknownOption() - .on('--help', function () { - console.log(' Only ' + chalk.green('') + ' is required.'); + .on('--help', () => { + console.log(` Only ${chalk.green('')} is required.`); console.log(); - console.log(' A custom ' + chalk.cyan('--scripts-version') + ' can be one of:'); - console.log(' - a specific npm version: ' + chalk.green('0.8.2')); - console.log(' - 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')); - console.log(' It is not needed unless you specifically want to use a fork.'); + console.log(` A custom ${chalk.cyan('--scripts-version')} can be one of:`); + console.log(` - a specific npm version: ${chalk.green('0.8.2')}`); + console.log(` - 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')}`); + console.log(` It is not needed unless you specifically want to use a fork.`); console.log(); - console.log(' 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')); + console.log(` 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')}`); console.log(); }) .parse(process.argv); if (typeof projectName === 'undefined') { console.error('Please specify the project directory:'); - console.log(' ' + chalk.cyan(program.name()) + chalk.green(' ')); + console.log(` ${chalk.cyan(program.name())} ${chalk.green('')}`); console.log(); console.log('For example:'); - console.log(' ' + chalk.cyan(program.name()) + chalk.green(' my-react-app')); + console.log(` ${chalk.cyan(program.name())} ${chalk.green('my-react-app')}`); console.log(); - console.log('Run ' + chalk.cyan(program.name() + ' --help') + ' to see all options.'); + console.log(`Run ${chalk.cyan(`${program.name()} --help`)} to see all options.`); process.exit(1); } function printValidationResults(results) { if (typeof results !== 'undefined') { - results.forEach(function (error) { - console.error(chalk.red(' * ' + error)); + results.forEach(error => { + console.error(chalk.red(` * ${error}`)); }); } } -var hiddenProgram = new commander.Command() +const hiddenProgram = new commander.Command() .option('--internal-testing-template ', '(internal usage only, DO NOT RELY ON THIS) ' + 'use a non-standard application template') .parse(process.argv) @@ -118,23 +75,23 @@ var hiddenProgram = new commander.Command() createApp(projectName, program.verbose, program.scriptsVersion, hiddenProgram.internalTestingTemplate); function createApp(name, verbose, version, template) { - var root = path.resolve(name); - var appName = path.basename(root); + const root = path.resolve(name); + const appName = path.basename(root); checkAppName(appName); fs.ensureDirSync(name); if (!isSafeToCreateProjectIn(root)) { - console.log('The directory ' + chalk.green(name) + ' contains files that could conflict.'); + console.log(`The directory ${chalk.green(name)} contains files that could conflict.`); console.log('Try using a new directory name.'); process.exit(1); } console.log( - 'Creating a new React app in ' + chalk.green(root) + '.' + `Creating a new React app in ${chalk.green(root)}.` ); console.log(); - var packageJson = { + const packageJson = { name: appName, version: '0.1.0', private: true @@ -143,7 +100,7 @@ function createApp(name, verbose, version, template) { path.join(root, 'package.json'), JSON.stringify(packageJson, null, 2) ); - var originalDirectory = process.cwd(); + const originalDirectory = process.cwd(); process.chdir(root); run(root, appName, version, verbose, originalDirectory, template); @@ -159,9 +116,9 @@ function shouldUseYarn() { } function install(useYarn, dependencies, verbose, isOnline) { - return new Promise(function(resolve, reject) { - var command; - var args; + return new Promise((resolve, reject) => { + let command; + let args; if (useYarn) { command = 'yarnpkg'; args = [ @@ -189,11 +146,11 @@ function install(useYarn, dependencies, verbose, isOnline) { args.push('--verbose'); } - var child = spawn(command, args, {stdio: 'inherit'}); - child.on('close', function(code) { + const child = spawn(command, args, {stdio: 'inherit'}); + child.on('close', code => { if (code !== 0) { reject({ - command: command + ' ' + args.join(' ') + command: `${command} ${args.join(' ')}` }); return; } @@ -203,35 +160,29 @@ function install(useYarn, dependencies, verbose, isOnline) { } function run(root, appName, version, verbose, originalDirectory, template) { - var packageToInstall = getInstallPackage(version); - var allDependencies = ['react', 'react-dom', packageToInstall]; + const packageToInstall = getInstallPackage(version); + const allDependencies = ['react', 'react-dom', packageToInstall]; console.log('Installing packages. This might take a couple minutes.'); - var useYarn = shouldUseYarn(); + const useYarn = shouldUseYarn(); getPackageName(packageToInstall) - .then(function(packageName) { - return checkIfOnline(useYarn).then(function(isOnline) { - return { - isOnline: isOnline, - packageName: packageName, - }; - }); - }) - .then(function(info) { - var isOnline = info.isOnline; - var packageName = info.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(); - return install(useYarn, allDependencies, verbose, isOnline).then(function() { - return packageName; - }); + return install(useYarn, allDependencies, verbose, isOnline).then(() => packageName); }) - .then(function(packageName) { + .then(packageName => { checkNodeVersion(packageName); // Since react-scripts has been installed with --save @@ -239,21 +190,21 @@ function run(root, appName, version, verbose, originalDirectory, template) { // also ensure react dependencies have caret version range fixDependencies(packageName); - var scriptsPath = path.resolve( + const scriptsPath = path.resolve( process.cwd(), 'node_modules', packageName, 'scripts', 'init.js' ); - var init = require(scriptsPath); + const init = require(scriptsPath); init(root, appName, verbose, originalDirectory, template); }) - .catch(function(reason) { + .catch(reason => { console.log(); console.log('Aborting installation.'); if (reason.command) { - console.log(' ' + chalk.cyan(reason.command), 'has failed.') + console.log(` ${chalk.cyan(reason.command)} has failed.`) } else { console.log(chalk.red('Unexpected error. Please report it as a bug:')); console.log(reason); @@ -261,24 +212,24 @@ function run(root, appName, version, verbose, originalDirectory, template) { console.log(); // On 'exit' we will delete these files from target directory. - var knownGeneratedFiles = [ + const knownGeneratedFiles = [ 'package.json', 'npm-debug.log', 'yarn-error.log', 'yarn-debug.log', 'node_modules' ]; - var currentFiles = fs.readdirSync(path.join(root)); - currentFiles.forEach(function (file) { - knownGeneratedFiles.forEach(function (fileToMatch) { + const currentFiles = fs.readdirSync(path.join(root)); + currentFiles.forEach(file => { + knownGeneratedFiles.forEach(fileToMatch => { // This will catch `(npm-debug|yarn-error|yarn-debug).log*` files // and the rest of knownGeneratedFiles. if ((fileToMatch.match(/.log/g) && file.indexOf(fileToMatch) === 0) || file === fileToMatch) { - console.log('Deleting generated file...', chalk.cyan(file)); + console.log(`Deleting generated file... ${chalk.cyan(file)}`); fs.removeSync(path.join(root, file)); } }); }); - var remainingFiles = fs.readdirSync(path.join(root)); + const remainingFiles = fs.readdirSync(path.join(root)); if (!remainingFiles.length) { // Delete target folder if empty - console.log('Deleting', chalk.cyan(appName + '/'), 'from', chalk.cyan(path.resolve(root, '..'))); + console.log(`Deleting ${chalk.cyan(`${appName} /`)} from ${chalk.cyan(path.resolve(root, '..'))}`); process.chdir(path.resolve(root, '..')); fs.removeSync(path.join(root)); } @@ -288,10 +239,10 @@ function run(root, appName, version, verbose, originalDirectory, template) { } function getInstallPackage(version) { - var packageToInstall = 'react-scripts'; - var validSemver = semver.valid(version); + let packageToInstall = 'react-scripts'; + const validSemver = semver.valid(version); if (validSemver) { - packageToInstall += '@' + validSemver; + packageToInstall += `@${validSemver}`; } else if (version) { // for tar.gz or alternative paths packageToInstall = version; @@ -300,16 +251,16 @@ function getInstallPackage(version) { } function getTemporaryDirectory() { - return new Promise(function(resolve, reject) { + return new Promise((resolve, reject) => { // Unsafe cleanup lets us recursively delete the directory if it contains // contents; by default it only allows removal if it's empty - tmp.dir({ unsafeCleanup: true }, function(err, tmpdir, callback) { + tmp.dir({ unsafeCleanup: true }, (err, tmpdir, callback) => { if (err) { reject(err); } else { resolve({ tmpdir: tmpdir, - cleanup: function() { + cleanup: () => { try { callback(); } catch (ignored) { @@ -324,8 +275,8 @@ function getTemporaryDirectory() { } function extractStream(stream, dest) { - return new Promise(function(resolve, reject) { - stream.pipe(unpack(dest, function(err) { + return new Promise((resolve, reject) => { + stream.pipe(unpack(dest, err => { if (err) { reject(err); } else { @@ -338,26 +289,24 @@ function extractStream(stream, dest) { // Extract package name from tarball url or path. function getPackageName(installPackage) { if (installPackage.indexOf('.tgz') > -1) { - return getTemporaryDirectory().then(function(obj) { - var stream; + return getTemporaryDirectory().then(obj => { + let stream; if (/^http/.test(installPackage)) { stream = hyperquest(installPackage); } else { stream = fs.createReadStream(installPackage); } - return extractStream(stream, obj.tmpdir).then(function() { - return obj; - }); - }).then(function(obj) { - var packageName = require(path.join(obj.tmpdir, 'package.json')).name; + return extractStream(stream, obj.tmpdir).then(() => obj); + }).then(obj => { + const packageName = require(path.join(obj.tmpdir, 'package.json')).name; obj.cleanup(); return packageName; - }).catch(function(err) { + }).catch(err => { // The package name could be with or without semver version, e.g. react-scripts-0.2.0-alpha.1.tgz // However, this function returns package name only without semver version. - console.log('Could not extract the package name from the archive: ' + err.message); - var assumedProjectName = installPackage.match(/^.+\/(.+?)(?:-\d+.+)?\.tgz$/)[1]; - console.log('Based on the filename, assuming it is "' + chalk.cyan(assumedProjectName) + '"'); + console.log(`Could not extract the package name from the archive: ${err.message}`); + const assumedProjectName = installPackage.match(/^.+\/(.+?)(?:-\d+.+)?\.tgz$/)[1]; + console.log(`Based on the filename, assuming it is "${chalk.cyan(assumedProjectName)}"`); return Promise.resolve(assumedProjectName); }); } else if (installPackage.indexOf('git+') === 0) { @@ -373,9 +322,9 @@ function getPackageName(installPackage) { } function checkNpmVersion() { - var isNpm2 = false; + let isNpm2 = false; try { - var npmVersion = execSync('npm --version').toString(); + const npmVersion = execSync('npm --version').toString(); isNpm2 = semver.lt(npmVersion, '3.0.0'); } catch (err) { return; @@ -392,13 +341,13 @@ function checkNpmVersion() { } function checkNodeVersion(packageName) { - var packageJsonPath = path.resolve( + const packageJsonPath = path.resolve( process.cwd(), 'node_modules', packageName, 'package.json' ); - var packageJson = require(packageJsonPath); + const packageJson = require(packageJsonPath); if (!packageJson.engines || !packageJson.engines.node) { return; } @@ -418,28 +367,26 @@ function checkNodeVersion(packageName) { } function checkAppName(appName) { - var validationResult = validateProjectName(appName); + const validationResult = validateProjectName(appName); if (!validationResult.validForNewPackages) { - console.error('Could not create a project called ' + chalk.red('"' + appName + '"') + ' because of npm naming restrictions:'); + console.error(`Could not create a project called ${chalk.red(`"${appName}"`)} because of npm naming restrictions:`); printValidationResults(validationResult.errors); printValidationResults(validationResult.warnings); process.exit(1); } // TODO: there should be a single place that holds the dependencies - var dependencies = ['react', 'react-dom']; - var devDependencies = ['react-scripts']; - var allDependencies = dependencies.concat(devDependencies).sort(); + const dependencies = ['react', 'react-dom']; + const devDependencies = ['react-scripts']; + const allDependencies = dependencies.concat(devDependencies).sort(); if (allDependencies.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' + - 'Due to the way npm works, the following names are not allowed:\n\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( - allDependencies.map(function(depName) { - return ' ' + depName; - }).join('\n') + allDependencies.map(depName => ` ${depName}`).join('\n') ) + chalk.red('\n\nPlease choose a different project name.') ); @@ -448,20 +395,20 @@ function checkAppName(appName) { } function makeCaretRange(dependencies, name) { - var version = dependencies[name]; + const version = dependencies[name]; if (typeof version === 'undefined') { console.error( - chalk.red('Missing ' + name + ' dependency in package.json') + chalk.red(`Missing ${name} dependency in package.json`) ); process.exit(1); } - var patchedVersion = '^' + version; + let patchedVersion = `^${version}`; 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; } @@ -470,8 +417,8 @@ function makeCaretRange(dependencies, name) { } function fixDependencies(packageName) { - var packagePath = path.join(process.cwd(), 'package.json'); - var packageJson = require(packagePath); + const packagePath = path.join(process.cwd(), 'package.json'); + const packageJson = require(packagePath); if (typeof packageJson.dependencies === 'undefined') { console.error( @@ -480,11 +427,11 @@ function fixDependencies(packageName) { process.exit(1); } - var packageVersion = packageJson.dependencies[packageName]; + const packageVersion = packageJson.dependencies[packageName]; if (typeof packageVersion === 'undefined') { console.error( - chalk.red('Unable to find ' + packageName + ' in package.json') + chalk.red(`Unable to find ${packageName} in package.json`) ); process.exit(1); } @@ -503,13 +450,11 @@ function fixDependencies(packageName) { // We also special case IJ-based products .idea because it integrates with CRA: // https://github.com/facebookincubator/create-react-app/pull/368#issuecomment-243446094 function isSafeToCreateProjectIn(root) { - var validFiles = [ + const validFiles = [ '.DS_Store', 'Thumbs.db', '.git', '.gitignore', '.idea', 'README.md', 'LICENSE', 'web.iml' ]; return fs.readdirSync(root) - .every(function(file) { - return validFiles.indexOf(file) >= 0; - }); + .every(file => validFiles.indexOf(file) >= 0); } function checkIfOnline(useYarn) { @@ -519,8 +464,8 @@ function checkIfOnline(useYarn) { return Promise.resolve(true); } - return new Promise(function(resolve) { - dns.resolve('registry.yarnpkg.com', function(err) { + return new Promise((resolve) => { + dns.resolve('registry.yarnpkg.com', err => { resolve(err === null); }); }); diff --git a/packages/create-react-app/index.js b/packages/create-react-app/index.js new file mode 100755 index 00000000000..412d4baaaa8 --- /dev/null +++ b/packages/create-react-app/index.js @@ -0,0 +1,55 @@ +#!/usr/bin/env node + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// /!\ DO NOT MODIFY THIS FILE /!\ +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// create-react-app is installed globally on people's computers. This means +// that it is extremely difficult to have them upgrade the version and +// because there's only one global version installed, it is very prone to +// breaking changes. +// +// The only job of create-react-app is to init the repository and then +// forward all the commands to the local version of create-react-app. +// +// If you need to add a new command, please add it to the scripts/ folder. +// +// The only reason to modify this file is to add more warnings and +// troubleshooting information for the `create-react-app` command. +// +// Do not make breaking changes! We absolutely don't want to have to +// tell people to update their global version of create-react-app. +// +// Also be careful with new language features. +// This file must work on Node 0.10+. +// +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// /!\ DO NOT MODIFY THIS FILE /!\ +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +'use strict'; + +var chalk = require('chalk'); + +var currentNodeVersion = process.versions.node; +if (currentNodeVersion.split('.')[0] < 4) { + console.error( + chalk.red( + 'You are running Node ' + currentNodeVersion + '.\n' + + 'Create React App requires Node 4 or higher. \n' + + 'Please update your version of Node.' + ) + ); + process.exit(1); +} + +require('./createReactApp'); diff --git a/packages/create-react-app/package.json b/packages/create-react-app/package.json index 4450add254c..918fcbefa56 100644 --- a/packages/create-react-app/package.json +++ b/packages/create-react-app/package.json @@ -14,7 +14,8 @@ "url": "https://github.com/facebookincubator/create-react-app/issues" }, "files": [ - "index.js" + "index.js", + "createReactApp.js" ], "bin": { "create-react-app": "./index.js" diff --git a/packages/react-scripts/config/env.js b/packages/react-scripts/config/env.js index 5f49ffaa17a..50ac6556476 100644 --- a/packages/react-scripts/config/env.js +++ b/packages/react-scripts/config/env.js @@ -12,11 +12,10 @@ // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be // injected into the application via DefinePlugin in Webpack configuration. - -var REACT_APP = /^REACT_APP_/i; +const REACT_APP = /^REACT_APP_/i; function getClientEnvironment(publicUrl) { - var raw = Object + const raw = Object .keys(process.env) .filter(key => REACT_APP.test(key)) .reduce((env, key) => { @@ -33,7 +32,7 @@ function getClientEnvironment(publicUrl) { 'PUBLIC_URL': publicUrl }); // Stringify all values so we can feed into Webpack DefinePlugin - var stringified = { + const stringified = { 'process.env': Object .keys(raw) .reduce((env, key) => { diff --git a/packages/react-scripts/config/jest/babelTransform.js b/packages/react-scripts/config/jest/babelTransform.js index 838d0ca9175..ab212e99ecc 100644 --- a/packages/react-scripts/config/jest/babelTransform.js +++ b/packages/react-scripts/config/jest/babelTransform.js @@ -6,7 +6,6 @@ * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ - 'use strict'; const babelJest = require('babel-jest'); diff --git a/packages/react-scripts/config/jest/fileTransform.js b/packages/react-scripts/config/jest/fileTransform.js index 060ee259de2..89027bdc702 100644 --- a/packages/react-scripts/config/jest/fileTransform.js +++ b/packages/react-scripts/config/jest/fileTransform.js @@ -16,6 +16,6 @@ const path = require('path'); module.exports = { process(src, filename) { - return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';'; + return `module.exports = ${JSON.stringify(path.basename(filename))};`; }, }; diff --git a/packages/react-scripts/config/paths.js b/packages/react-scripts/config/paths.js index 83f234d6c62..0eba073ae96 100644 --- a/packages/react-scripts/config/paths.js +++ b/packages/react-scripts/config/paths.js @@ -10,13 +10,13 @@ // @remove-on-eject-end 'use strict'; -var path = require('path'); -var fs = require('fs'); -var url = require('url'); +const path = require('path'); +const fs = require('fs'); +const url = require('url'); // Make sure any symlinks in the project folder are resolved: // https://github.com/facebookincubator/create-react-app/issues/637 -var appDirectory = fs.realpathSync(process.cwd()); +const appDirectory = fs.realpathSync(process.cwd()); function resolveApp(relativePath) { return path.resolve(appDirectory, relativePath); } @@ -36,20 +36,20 @@ function resolveApp(relativePath) { // Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. // https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421 -var nodePaths = (process.env.NODE_PATH || '') +const nodePaths = (process.env.NODE_PATH || '') .split(process.platform === 'win32' ? ';' : ':') .filter(Boolean) .filter(folder => !path.isAbsolute(folder)) .map(resolveApp); -var envPublicUrl = process.env.PUBLIC_URL; +const envPublicUrl = process.env.PUBLIC_URL; function ensureSlash(path, needsSlash) { - var hasSlash = path.endsWith('/'); + const hasSlash = path.endsWith('/'); if (hasSlash && !needsSlash) { return path.substr(path, path.length - 1); } else if (!hasSlash && needsSlash) { - return path + '/'; + return `${path}/`; } else { return path; } @@ -66,8 +66,8 @@ function getPublicUrl(appPackageJson) { // We can't use a relative path in HTML because we don't want to load something // like /todos/42/static/js/bundle.7289d.js. We have to know the root. function getServedPath(appPackageJson) { - var publicUrl = getPublicUrl(appPackageJson); - var servedUrl = envPublicUrl || ( + const publicUrl = getPublicUrl(appPackageJson); + const servedUrl = envPublicUrl || ( publicUrl ? url.parse(publicUrl).pathname : '/' ); return ensureSlash(servedUrl, true); @@ -114,9 +114,9 @@ module.exports = { ownNodeModules: resolveOwn('node_modules'), // This is empty on npm 3 }; -var ownPackageJson = require('../package.json'); -var reactScriptsPath = resolveApp(`node_modules/${ownPackageJson.name}`); -var reactScriptsLinked = fs.existsSync(reactScriptsPath) && fs.lstatSync(reactScriptsPath).isSymbolicLink(); +const ownPackageJson = require('../package.json'); +const reactScriptsPath = resolveApp(`node_modules/${ownPackageJson.name}`); +const reactScriptsLinked = fs.existsSync(reactScriptsPath) && fs.lstatSync(reactScriptsPath).isSymbolicLink(); // config before publish: we're in ./packages/react-scripts/config/ if (!reactScriptsLinked && __dirname.indexOf(path.join('packages', 'react-scripts', 'config')) !== -1) { diff --git a/packages/react-scripts/config/webpack.config.dev.js b/packages/react-scripts/config/webpack.config.dev.js index 214373b81b8..0fe461599d7 100644 --- a/packages/react-scripts/config/webpack.config.dev.js +++ b/packages/react-scripts/config/webpack.config.dev.js @@ -10,29 +10,29 @@ // @remove-on-eject-end 'use strict'; -var autoprefixer = require('autoprefixer'); -var webpack = require('webpack'); -var HtmlWebpackPlugin = require('html-webpack-plugin'); -var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); -var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); -var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); -var getClientEnvironment = require('./env'); -var paths = require('./paths'); +const autoprefixer = require('autoprefixer'); +const webpack = require('webpack'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); +const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); +const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); +const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); +const getClientEnvironment = require('./env'); +const paths = require('./paths'); // @remove-on-eject-begin // `path` is not used after eject - see https://github.com/facebookincubator/create-react-app/issues/1174 -var path = require('path'); +const path = require('path'); // @remove-on-eject-end // Webpack uses `publicPath` to determine where the app is being served from. // In development, we always serve from the root. This makes config easier. -var publicPath = '/'; +const publicPath = '/'; // `publicUrl` is just like `publicPath`, but we will provide it to our app // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz. -var publicUrl = ''; +const publicUrl = ''; // Get environment variables to inject into our app. -var env = getClientEnvironment(publicUrl); +const env = getClientEnvironment(publicUrl); // This is the development configuration. // It is focused on developer experience and fast rebuilds. @@ -202,18 +202,16 @@ module.exports = { loader: 'postcss-loader', options: { ident: 'postcss', // https://webpack.js.org/guides/migrating/#complex-options - plugins: function () { - return [ - autoprefixer({ - browsers: [ - '>1%', - 'last 4 versions', - 'Firefox ESR', - 'not ie < 9', // React doesn't support IE8 anyway - ] - }) - ] - } + plugins: () => ([ + autoprefixer({ + browsers: [ + '>1%', + 'last 4 versions', + 'Firefox ESR', + 'not ie < 9', // React doesn't support IE8 anyway + ] + }) + ]) } } ] diff --git a/packages/react-scripts/config/webpack.config.prod.js b/packages/react-scripts/config/webpack.config.prod.js index 5a2388d29c3..dfa2b4a0ed6 100644 --- a/packages/react-scripts/config/webpack.config.prod.js +++ b/packages/react-scripts/config/webpack.config.prod.js @@ -10,32 +10,32 @@ // @remove-on-eject-end 'use strict'; -var autoprefixer = require('autoprefixer'); -var webpack = require('webpack'); -var HtmlWebpackPlugin = require('html-webpack-plugin'); -var ExtractTextPlugin = require('extract-text-webpack-plugin'); -var ManifestPlugin = require('webpack-manifest-plugin'); -var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); -var paths = require('./paths'); -var getClientEnvironment = require('./env'); +const autoprefixer = require('autoprefixer'); +const webpack = require('webpack'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); +const ExtractTextPlugin = require('extract-text-webpack-plugin'); +const ManifestPlugin = require('webpack-manifest-plugin'); +const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); +const paths = require('./paths'); +const getClientEnvironment = require('./env'); // @remove-on-eject-begin // `path` is not used after eject - see https://github.com/facebookincubator/create-react-app/issues/1174 -var path = require('path'); +const path = require('path'); // @remove-on-eject-end // Webpack uses `publicPath` to determine where the app is being served from. // It requires a trailing slash, or the file assets will get an incorrect path. -var publicPath = paths.servedPath; +const publicPath = paths.servedPath; // Some apps do not use client-side routing with pushState. // For these, "homepage" can be set to "." to enable relative asset paths. -var shouldUseRelativeAssetPaths = publicPath === './'; +const shouldUseRelativeAssetPaths = publicPath === './'; // `publicUrl` is just like `publicPath`, but we will provide it to our app // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz. -var publicUrl = publicPath.slice(0, -1); +const publicUrl = publicPath.slice(0, -1); // Get environment variables to inject into our app. -var env = getClientEnvironment(publicUrl); +const env = getClientEnvironment(publicUrl); // Assert this just to be safe. // Development builds of React are slow and not intended for production. @@ -209,18 +209,16 @@ module.exports = { loader: 'postcss-loader', options: { ident: 'postcss', // https://webpack.js.org/guides/migrating/#complex-options - plugins: function () { - return [ - autoprefixer({ - browsers: [ - '>1%', - 'last 4 versions', - 'Firefox ESR', - 'not ie < 9', // React doesn't support IE8 anyway - ] - }) - ] - } + plugins: () => ([ + autoprefixer({ + browsers: [ + '>1%', + 'last 4 versions', + 'Firefox ESR', + 'not ie < 9', // React doesn't support IE8 anyway + ] + }) + ]) } } ] diff --git a/packages/react-scripts/config/webpackDevServer.config.js b/packages/react-scripts/config/webpackDevServer.config.js index 89fd48bc524..910f074fab5 100644 --- a/packages/react-scripts/config/webpackDevServer.config.js +++ b/packages/react-scripts/config/webpackDevServer.config.js @@ -10,11 +10,11 @@ // @remove-on-eject-end 'use strict'; -var config = require('./webpack.config.dev'); -var paths = require('./paths'); +const config = require('./webpack.config.dev'); +const paths = require('./paths'); -var protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; -var host = process.env.HOST || 'localhost'; +const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; +const host = process.env.HOST || 'localhost'; module.exports = { // Enable gzip compression of generated files. diff --git a/packages/react-scripts/fixtures/kitchensink/src/features/syntax/ComputedProperties.js b/packages/react-scripts/fixtures/kitchensink/src/features/syntax/ComputedProperties.js index e345283eaaa..6e8c2c1ff1d 100644 --- a/packages/react-scripts/fixtures/kitchensink/src/features/syntax/ComputedProperties.js +++ b/packages/react-scripts/fixtures/kitchensink/src/features/syntax/ComputedProperties.js @@ -11,10 +11,10 @@ import React, { Component, PropTypes } from 'react' function load(prefix) { return [ - { id: 1, [prefix + 'name']: '1' }, - { id: 2, [prefix + 'name']: '2' }, - { id: 3, [prefix + 'name']: '3' }, - { id: 4, [prefix + 'name']: '4' } + { id: 1, [`${prefix} name`]: '1' }, + { id: 2, [`${prefix} name`]: '2' }, + { id: 3, [`${prefix} name`]: '3' }, + { id: 4, [`${prefix} name`]: '4' } ]; } diff --git a/packages/react-scripts/scripts/build.js b/packages/react-scripts/scripts/build.js index 05cefa0393e..b6c6ddf893d 100644 --- a/packages/react-scripts/scripts/build.js +++ b/packages/react-scripts/scripts/build.js @@ -19,19 +19,19 @@ process.env.NODE_ENV = 'production'; // https://github.com/motdotla/dotenv require('dotenv').config({silent: true}); -var chalk = require('chalk'); -var fs = require('fs-extra'); -var path = require('path'); -var url = require('url'); -var webpack = require('webpack'); -var config = require('../config/webpack.config.prod'); -var paths = require('../config/paths'); -var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); -var FileSizeReporter = require('react-dev-utils/FileSizeReporter'); -var measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild; -var printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; - -var useYarn = fs.existsSync(paths.yarnLockFile); +const chalk = require('chalk'); +const fs = require('fs-extra'); +const path = require('path'); +const url = require('url'); +const webpack = require('webpack'); +const config = require('../config/webpack.config.prod'); +const paths = require('../config/paths'); +const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); +const FileSizeReporter = require('react-dev-utils/FileSizeReporter'); + +const measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild; +const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; +const useYarn = fs.existsSync(paths.yarnLockFile); // Warn and crash if required files are missing if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { @@ -66,7 +66,7 @@ function printErrors(summary, errors) { function build(previousFileSizes) { console.log('Creating an optimized production build...'); - var compiler; + let compiler; try { compiler = webpack(config); } catch (err) { @@ -98,74 +98,74 @@ function build(previousFileSizes) { printFileSizesAfterBuild(stats, previousFileSizes); console.log(); - var openCommand = process.platform === 'win32' ? 'start' : 'open'; - var appPackage = require(paths.appPackageJson); - var publicUrl = paths.publicUrl; - var publicPath = config.output.publicPath; - var publicPathname = url.parse(publicPath).pathname; + const openCommand = process.platform === 'win32' ? 'start' : 'open'; + const appPackage = require(paths.appPackageJson); + const publicUrl = paths.publicUrl; + const publicPath = config.output.publicPath; + const publicPathname = url.parse(publicPath).pathname; 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) + '.'); - console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.'); + console.log(`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')}.`); console.log(); - console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.'); - console.log('To publish it at ' + chalk.green(publicUrl) + ', run:'); + console.log(`The ${chalk.cyan('build')} folder is ready to be deployed.`); + console.log(`To publish it at ${chalk.green(publicUrl)}, run:`); // If script deploy has been added to package.json, skip the instructions if (typeof appPackage.scripts.deploy === 'undefined') { console.log(); if (useYarn) { - console.log(' ' + chalk.cyan('yarn') + ' add --dev gh-pages'); + console.log(` ${chalk.cyan('yarn')} add --dev gh-pages`); } else { - console.log(' ' + chalk.cyan('npm') + ' install --save-dev gh-pages'); + 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(`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(` ${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'); + console.log(` ${chalk.cyan(useYarn ? 'yarn' : 'npm')} run deploy`); console.log(); } else if (publicPath !== '/') { // "homepage": "http://mywebsite.com/project" - console.log('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') + '.'); + console.log(`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')}.`); console.log(); - console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.'); + console.log(`The ${chalk.cyan('build')} folder is ready to be deployed.`); console.log(); } else { if (publicUrl) { // "homepage": "http://mywebsite.com" - console.log('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') + '.'); + console.log(`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')}.`); console.log(); } else { // no homepage console.log('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') + '.'); + console.log(`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(',')); + console.log(` ${chalk.green('"homepage"')} ${chalk.cyan(':')} ${chalk.green('"http://myname.github.io/myapp"')}${chalk.cyan(',')}`); console.log(); } - var build = path.relative(process.cwd(), paths.appBuild); - console.log('The ' + chalk.cyan(build) + ' folder is ready to be deployed.'); + const build = path.relative(process.cwd(), paths.appBuild); + console.log(`The ${chalk.cyan(build)} folder is ready to be deployed.`); console.log('You may also serve it locally with a static server:') console.log(); if (useYarn) { - console.log(' ' + chalk.cyan('yarn') + ' global add pushstate-server'); + console.log(` ${chalk.cyan('yarn')} global add pushstate-server`); } else { - console.log(' ' + chalk.cyan('npm') + ' install -g pushstate-server'); + console.log(` ${chalk.cyan('npm')} install -g pushstate-server`); } - console.log(' ' + chalk.cyan('pushstate-server') + ' ' + build); - console.log(' ' + chalk.cyan(openCommand) + ' http://localhost:' + (process.env.PORT || 9000)); + console.log(` ${chalk.cyan('pushstate-server')} build`); + console.log(` ${chalk.cyan(openCommand)} http://localhost:${(process.env.PORT || 9000)}`); console.log(); } }); diff --git a/packages/react-scripts/scripts/eject.js b/packages/react-scripts/scripts/eject.js index 39a40546bde..5b801dd9bd9 100644 --- a/packages/react-scripts/scripts/eject.js +++ b/packages/react-scripts/scripts/eject.js @@ -9,16 +9,16 @@ */ 'use strict'; -var fs = require('fs-extra'); -var path = require('path'); -var spawnSync = require('cross-spawn').sync; -var chalk = require('chalk'); -var prompt = require('react-dev-utils/prompt'); -var paths = require('../config/paths'); -var createJestConfig = require('./utils/createJestConfig'); +const fs = require('fs-extra'); +const path = require('path'); +const spawnSync = require('cross-spawn').sync; +const chalk = require('chalk'); +const prompt = require('react-dev-utils/prompt'); +const paths = require('../config/paths'); +const createJestConfig = require('./utils/createJestConfig'); -var green = chalk.green; -var cyan = chalk.cyan; +const green = chalk.green; +const cyan = chalk.cyan; prompt( 'Are you sure you want to eject? This action is permanent.', @@ -31,13 +31,13 @@ prompt( console.log('Ejecting...'); - var ownPath = paths.ownPath; - var appPath = paths.appPath; + const ownPath = paths.ownPath; + const appPath = paths.appPath; function verifyAbsent(file) { if (fs.existsSync(path.join(appPath, file))) { console.error( - '`' + file + '` already exists in your app folder. We cannot ' + + `\`${file}\` already exists in your app folder. We cannot ` + 'continue as you would lose all the changes in that file or directory. ' + 'Please move or delete it (maybe make a copy for backup) and run this ' + 'command again.' @@ -46,7 +46,7 @@ prompt( } } - var folders = [ + const folders = [ 'config', 'config/jest', 'scripts', @@ -54,7 +54,7 @@ prompt( ]; // Make shallow array of files paths - var files = folders.reduce(function (files, folder) { + const files = folders.reduce((files, folder) => { return files.concat( fs.readdirSync(path.join(ownPath, folder)) // set full path @@ -69,14 +69,14 @@ prompt( files.forEach(verifyAbsent); console.log(); - console.log(cyan('Copying files into ' + appPath)); + console.log(cyan(`Copying files into ${appPath}`)); - folders.forEach(function(folder) { + folders.forEach(folder => { fs.mkdirSync(path.join(appPath, folder)) }); - files.forEach(function(file) { - var content = fs.readFileSync(file, 'utf8'); + files.forEach(file => { + let content = fs.readFileSync(file, 'utf8'); // Skip flagged files if (content.match(/\/\/ @remove-file-on-eject/)) { @@ -88,48 +88,45 @@ prompt( // Remove dead code from .applescript files on eject .replace(/-- @remove-on-eject-begin([\s\S]*?)-- @remove-on-eject-end/mg, '') .trim() + '\n'; - console.log(' Adding ' + cyan(file.replace(ownPath, '')) + ' to the project'); + console.log(` Adding ${cyan(file.replace(ownPath, ''))} to the project`); fs.writeFileSync(file.replace(ownPath, appPath), content); }); console.log(); - var ownPackage = require(path.join(ownPath, 'package.json')); - var appPackage = require(path.join(appPath, 'package.json')); - var babelConfig = JSON.parse(fs.readFileSync(path.join(ownPath, 'babelrc'), 'utf8')); - var eslintConfig = JSON.parse(fs.readFileSync(path.join(ownPath, 'eslintrc'), 'utf8')); + const ownPackage = require(path.join(ownPath, 'package.json')); + const appPackage = require(path.join(appPath, 'package.json')); + const babelConfig = JSON.parse(fs.readFileSync(path.join(ownPath, '.babelrc'), 'utf8')); + const eslintConfig = JSON.parse(fs.readFileSync(path.join(ownPath, '.eslintrc'), 'utf8')); console.log(cyan('Updating the dependencies')); - var ownPackageName = ownPackage.name; + const ownPackageName = ownPackage.name; if (appPackage.devDependencies[ownPackageName]) { - console.log(' Removing ' + cyan(ownPackageName) + ' from devDependencies'); + console.log(` Removing ${cyan(ownPackageName)} from devDependencies`); delete appPackage.devDependencies[ownPackageName]; } if (appPackage.dependencies[ownPackageName]) { - console.log(' Removing ' + cyan(ownPackageName) + ' from dependencies'); + console.log(` Removing ${cyan(ownPackageName)} from dependencies`); delete appPackage.dependencies[ownPackageName]; } - Object.keys(ownPackage.dependencies).forEach(function (key) { + Object.keys(ownPackage.dependencies).forEach(key => { // For some reason optionalDependencies end up in dependencies after install if (ownPackage.optionalDependencies[key]) { return; } - console.log(' Adding ' + cyan(key) + ' to devDependencies'); + console.log(` Adding ${cyan(key)} to devDependencies`); appPackage.devDependencies[key] = ownPackage.dependencies[key]; }); console.log(); console.log(cyan('Updating the scripts')); delete appPackage.scripts['eject']; - Object.keys(appPackage.scripts).forEach(function (key) { - Object.keys(ownPackage.bin).forEach(function (binKey) { - var regex = new RegExp(binKey + ' (\\w+)', 'g'); + Object.keys(appPackage.scripts).forEach(key => { + Object.keys(ownPackage.bin).forEach(binKey => { + const regex = new RegExp(binKey + ' (\\w+)', 'g'); appPackage.scripts[key] = appPackage.scripts[key] .replace(regex, '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"`)}` ); }); }); @@ -137,7 +134,7 @@ prompt( console.log(); console.log(cyan('Configuring package.json')); // Add Jest config - console.log(' Adding ' + cyan('Jest') + ' configuration'); + console.log(` Adding ${cyan('Jest')} configuration`); appPackage.jest = createJestConfig( filePath => path.posix.join('', filePath), null, @@ -145,11 +142,11 @@ prompt( ); // Add Babel config - console.log(' Adding ' + cyan('Babel') + ' preset'); + console.log(` Adding ${cyan('Babel')} preset`); appPackage.babel = babelConfig; // Add ESlint config - console.log(' Adding ' + cyan('ESLint') +' configuration'); + console.log(` Adding ${cyan('ESLint')} configuration`); appPackage.eslintConfig = eslintConfig; fs.writeFileSync( @@ -162,7 +159,7 @@ prompt( if (ownPath.indexOf(appPath) === 0) { try { // remove react-scripts and react-scripts binaries from app node_modules - Object.keys(ownPackage.bin).forEach(function(binKey) { + Object.keys(ownPackage.bin).forEach(binKey => { fs.removeSync(path.join(appPath, 'node_modules', '.bin', binKey)); }); fs.removeSync(ownPath); diff --git a/packages/react-scripts/scripts/init.js b/packages/react-scripts/scripts/init.js index 352bf0f41c5..499885a2bf5 100644 --- a/packages/react-scripts/scripts/init.js +++ b/packages/react-scripts/scripts/init.js @@ -7,19 +7,18 @@ * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ - 'use strict'; -var fs = require('fs-extra'); -var path = require('path'); -var spawn = require('cross-spawn'); -var chalk = require('chalk'); +const fs = require('fs-extra'); +const path = require('path'); +const spawn = require('cross-spawn'); +const chalk = require('chalk'); module.exports = function(appPath, appName, verbose, originalDirectory, template) { - var ownPackageName = require(path.join(__dirname, '..', 'package.json')).name; - var ownPath = path.join(appPath, 'node_modules', ownPackageName); - var appPackage = require(path.join(appPath, 'package.json')); - var useYarn = fs.existsSync(path.join(appPath, 'yarn.lock')); + 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')); // Copy over some of the devDependencies appPackage.dependencies = appPackage.dependencies || {}; @@ -38,27 +37,27 @@ module.exports = function(appPath, appName, verbose, originalDirectory, template JSON.stringify(appPackage, null, 2) ); - var readmeExists = fs.existsSync(path.join(appPath, 'README.md')); + const readmeExists = fs.existsSync(path.join(appPath, 'README.md')); if (readmeExists) { fs.renameSync(path.join(appPath, 'README.md'), path.join(appPath, 'README.old.md')); } // Copy the files for the user - var templatePath = template ? path.resolve(originalDirectory, template) : path.join(ownPath, 'template'); + const templatePath = template ? path.resolve(originalDirectory, template) : path.join(ownPath, 'template'); if (fs.existsSync(templatePath)) { fs.copySync(templatePath, appPath); } else { - console.error('Could not locate supplied template: ' + chalk.green(templatePath)); + console.error(`Could not locate supplied template: ${chalk.green(templatePath)}`); return; } // Rename gitignore after the fact to prevent npm from renaming it to .npmignore // See: https://github.com/npm/npm/issues/1862 - fs.move(path.join(appPath, 'gitignore'), path.join(appPath, '.gitignore'), [], function (err) { + fs.move(path.join(appPath, 'gitignore'), path.join(appPath, '.gitignore'), [], err => { if (err) { // Append if there's already a `.gitignore` file there if (err.code === 'EEXIST') { - var data = fs.readFileSync(path.join(appPath, 'gitignore')); + const data = fs.readFileSync(path.join(appPath, 'gitignore')); fs.appendFileSync(path.join(appPath, '.gitignore'), data); fs.unlinkSync(path.join(appPath, 'gitignore')); } else { @@ -67,8 +66,8 @@ module.exports = function(appPath, appName, verbose, originalDirectory, template } }); - var command; - var args; + let command; + let args; if (useYarn) { command = 'yarnpkg'; @@ -79,16 +78,16 @@ module.exports = function(appPath, appName, verbose, originalDirectory, template 'install', '--save', verbose && '--verbose' - ].filter(function(e) { return e; }); + ].filter(e => e); } args.push('react', 'react-dom'); // Install additional template dependencies, if present - var templateDependenciesPath = path.join(appPath, '.template.dependencies.json'); + const templateDependenciesPath = path.join(appPath, '.template.dependencies.json'); if (fs.existsSync(templateDependenciesPath)) { - var templateDependencies = require(templateDependenciesPath).dependencies; - args = args.concat(Object.keys(templateDependencies).map(function (key) { - return key + '@' + templateDependencies[key]; + const templateDependencies = require(templateDependenciesPath).dependencies; + args = args.concat(Object.keys(templateDependencies).map(key => { + return `${key}@${templateDependencies[key]}`; })); fs.unlinkSync(templateDependenciesPath); } @@ -97,12 +96,12 @@ module.exports = function(appPath, appName, verbose, originalDirectory, template // which doesn't install react and react-dom along with react-scripts // or template is presetend (via --internal-testing-template) if (!isReactInstalled(appPackage) || template) { - console.log('Installing react and react-dom using ' + command + '...'); + console.log(`Installing react and react-dom using ${command}...`); console.log(); - var proc = spawn.sync(command, args, {stdio: 'inherit'}); + const proc = spawn.sync(command, args, {stdio: 'inherit'}); if (proc.status !== 0) { - console.error('`' + command + ' ' + args.join(' ') + '` failed'); + console.error(`\`${command} ${args.join(' ')}\` failed`); return; } } @@ -110,7 +109,7 @@ module.exports = function(appPath, appName, verbose, originalDirectory, template // Display the most elegant way to cd. // This needs to handle an undefined originalDirectory for // backward compatibility with old global-cli's. - var cdpath; + let cdpath; if (originalDirectory && path.join(originalDirectory, appName) === appPath) { cdpath = appName; @@ -122,26 +121,26 @@ module.exports = function(appPath, appName, verbose, originalDirectory, template var displayedCommand = useYarn ? 'yarn' : 'npm'; console.log(); - console.log('Success! Created ' + appName + ' at ' + appPath); + console.log(`Success! Created ${appName} at ${appPath}`); console.log('Inside that directory, you can run several commands:'); console.log(); - console.log(chalk.cyan(' ' + displayedCommand + ' start')); + console.log(chalk.cyan(` ${displayedCommand} start`)); console.log(' Starts the development server.'); console.log(); - console.log(chalk.cyan(' ' + displayedCommand + ' run build')); + console.log(chalk.cyan(` ${displayedCommand} run build`)); console.log(' Bundles the app into static files for production.'); console.log(); - console.log(chalk.cyan(' ' + displayedCommand + ' test')); + console.log(chalk.cyan(` ${displayedCommand} test`)); console.log(' Starts the test runner.'); console.log(); - console.log(chalk.cyan(' ' + displayedCommand + ' run eject')); + console.log(chalk.cyan(` ${displayedCommand} run eject`)); console.log(' Removes this tool and copies build dependencies, configuration files'); console.log(' and scripts into the app directory. If you do this, you can’t go back!'); console.log(); console.log('We suggest that you begin by typing:'); console.log(); console.log(chalk.cyan(' cd'), cdpath); - console.log(' ' + chalk.cyan(displayedCommand + ' start')); + console.log(` ${chalk.cyan(`${displayedCommand} start`)}`); if (readmeExists) { console.log(); console.log(chalk.yellow('You had a `README.md` file, we renamed it to `README.old.md`')); @@ -151,7 +150,7 @@ module.exports = function(appPath, appName, verbose, originalDirectory, template }; function isReactInstalled(appPackage) { - var dependencies = appPackage.dependencies || {}; + const dependencies = appPackage.dependencies || {}; return ( typeof dependencies.react !== 'undefined' && diff --git a/packages/react-scripts/scripts/start.js b/packages/react-scripts/scripts/start.js index 349871be747..8a66043afa2 100644 --- a/packages/react-scripts/scripts/start.js +++ b/packages/react-scripts/scripts/start.js @@ -8,7 +8,6 @@ * of patent rights can be found in the PATENTS file in the same directory. */ // @remove-on-eject-end - 'use strict'; process.env.NODE_ENV = 'development'; @@ -19,24 +18,24 @@ process.env.NODE_ENV = 'development'; // https://github.com/motdotla/dotenv require('dotenv').config({silent: true}); -var fs = require('fs'); -var chalk = require('chalk'); -var detect = require('detect-port'); -var WebpackDevServer = require('webpack-dev-server'); -var clearConsole = require('react-dev-utils/clearConsole'); -var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); -var getProcessForPort = require('react-dev-utils/getProcessForPort'); -var openBrowser = require('react-dev-utils/openBrowser'); -var prompt = require('react-dev-utils/prompt'); -var paths = require('../config/paths'); -var config = require('../config/webpack.config.dev'); -var devServerConfig = require('../config/webpackDevServer.config'); -var createWebpackCompiler = require('./utils/createWebpackCompiler'); -var addWebpackMiddleware = require('./utils/addWebpackMiddleware'); - -var useYarn = fs.existsSync(paths.yarnLockFile); -var cli = useYarn ? 'yarn' : 'npm'; -var isInteractive = process.stdout.isTTY; +const fs = require('fs'); +const chalk = require('chalk'); +const detect = require('detect-port'); +const WebpackDevServer = require('webpack-dev-server'); +const clearConsole = require('react-dev-utils/clearConsole'); +const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); +const getProcessForPort = require('react-dev-utils/getProcessForPort'); +const openBrowser = require('react-dev-utils/openBrowser'); +const prompt = require('react-dev-utils/prompt'); +const paths = require('../config/paths'); +const config = require('../config/webpack.config.dev'); +const devServerConfig = require('../config/webpackDevServer.config'); +const createWebpackCompiler = require('./utils/createWebpackCompiler'); +const addWebpackMiddleware = require('./utils/addWebpackMiddleware'); + +const useYarn = fs.existsSync(paths.yarnLockFile); +const cli = useYarn ? 'yarn' : 'npm'; +const isInteractive = process.stdout.isTTY; // Warn and crash if required files are missing if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { @@ -44,29 +43,29 @@ if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { } // Tools like Cloud9 rely on this. -var DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; +const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; function run(port) { - var protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; - var host = process.env.HOST || 'localhost'; + const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; + const host = process.env.HOST || 'localhost'; // Create a webpack compiler that is configured with custom messages. - var compiler = createWebpackCompiler(config, function onReady(showInstructions) { + const compiler = createWebpackCompiler(config, function onReady(showInstructions) { if (!showInstructions) { return; } console.log(); console.log('The app is running at:'); console.log(); - console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/')); + console.log(` ${chalk.cyan(`${protocol}://${host}:${port}/`)}`); console.log(); 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(); }); // Serve webpack assets generated by the compiler over a web sever. - var devServer = new WebpackDevServer(compiler, devServerConfig); + const devServer = new WebpackDevServer(compiler, devServerConfig); // Our custom middleware proxies requests to /index.html or a remote API. addWebpackMiddleware(devServer); @@ -83,7 +82,7 @@ function run(port) { console.log(chalk.cyan('Starting the development server...')); console.log(); - openBrowser(protocol + '://' + host + ':' + port + '/'); + openBrowser(`${protocol}://${host}:${port}/`); }); } @@ -97,11 +96,10 @@ detect(DEFAULT_PORT).then(port => { if (isInteractive) { clearConsole(); - var existingProcess = getProcessForPort(DEFAULT_PORT); - var question = - chalk.yellow('Something is already running on port ' + DEFAULT_PORT + '.' + - ((existingProcess) ? ' Probably:\n ' + existingProcess : '')) + - '\n\nWould you like to run the app on another port instead?'; + const existingProcess = getProcessForPort(DEFAULT_PORT); + const question = chalk.yellow(`Something is already running on port ${DEFAULT_PORT}.` + + `${existingProcess ? ` Probably:\n ${existingProcess}` : ''}`) + + '\n\nWould you like to run the app on another port instead?'; prompt(question, true).then(shouldChangePort => { if (shouldChangePort) { @@ -109,6 +107,6 @@ detect(DEFAULT_PORT).then(port => { } }); } 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}.`)); } }); diff --git a/packages/react-scripts/scripts/test.js b/packages/react-scripts/scripts/test.js index de3a9691897..7ff6a8f014f 100644 --- a/packages/react-scripts/scripts/test.js +++ b/packages/react-scripts/scripts/test.js @@ -8,7 +8,6 @@ * of patent rights can be found in the PATENTS file in the same directory. */ // @remove-on-eject-end - 'use strict'; process.env.NODE_ENV = 'test'; diff --git a/packages/react-scripts/scripts/utils/addWebpackMiddleware.js b/packages/react-scripts/scripts/utils/addWebpackMiddleware.js index b3ff2548458..7fce6fbafef 100644 --- a/packages/react-scripts/scripts/utils/addWebpackMiddleware.js +++ b/packages/react-scripts/scripts/utils/addWebpackMiddleware.js @@ -10,16 +10,16 @@ // @remove-on-eject-end 'use strict'; -var chalk = require('chalk'); -var historyApiFallback = require('connect-history-api-fallback'); -var httpProxyMiddleware = require('http-proxy-middleware'); -var paths = require('../../config/paths'); +const chalk = require('chalk'); +const historyApiFallback = require('connect-history-api-fallback'); +const httpProxyMiddleware = require('http-proxy-middleware'); +const paths = require('../../config/paths'); // We need to provide a custom onError function for httpProxyMiddleware. // It allows us to log custom error messages on the console. function onProxyError(proxy) { - return function(err, req, res){ - var host = req.headers && req.headers.host; + return (err, req, res) => { + const host = req.headers && req.headers.host; console.log( chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) + ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.' @@ -44,7 +44,7 @@ function onProxyError(proxy) { module.exports = function addWebpackMiddleware(devServer) { // `proxy` lets you to specify a fallback server during development. // Every unrecognized request will be forwarded to it. - var proxy = require(paths.appPackageJson).proxy; + const proxy = require(paths.appPackageJson).proxy; devServer.use(historyApiFallback({ // Paths with dots should still use the history fallback. // See https://github.com/facebookincubator/create-react-app/issues/387. @@ -74,14 +74,14 @@ module.exports = function addWebpackMiddleware(devServer) { // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading) // - /sockjs-node/* (WebpackDevServer uses this for hot reloading) // Tip: use https://jex.im/regulex/ to visualize the regex - var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/; + const mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/; // Pass the scope regex both to Express and to the middleware for proxying // of both HTTP and WebSockets to work without false positives. - var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), { + const hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), { target: proxy, logLevel: 'silent', - onProxyReq: function(proxyReq) { + onProxyReq: proxyReq => { // Browers may send Origin headers even with same-origin // requests. To prevent CORS issues, we have to change // the Origin to match the target URL. diff --git a/packages/react-scripts/scripts/utils/createJestConfig.js b/packages/react-scripts/scripts/utils/createJestConfig.js index 0174237a0f8..6eab4d7ad5d 100644 --- a/packages/react-scripts/scripts/utils/createJestConfig.js +++ b/packages/react-scripts/scripts/utils/createJestConfig.js @@ -7,7 +7,6 @@ * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ - 'use strict'; const fs = require('fs'); diff --git a/packages/react-scripts/scripts/utils/createWebpackCompiler.js b/packages/react-scripts/scripts/utils/createWebpackCompiler.js index 246f4b63cbe..a06dc375fda 100644 --- a/packages/react-scripts/scripts/utils/createWebpackCompiler.js +++ b/packages/react-scripts/scripts/utils/createWebpackCompiler.js @@ -10,19 +10,19 @@ // @remove-on-eject-end 'use strict'; -var chalk = require('chalk'); -var webpack = require('webpack'); -var clearConsole = require('react-dev-utils/clearConsole'); -var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); +const chalk = require('chalk'); +const webpack = require('webpack'); +const clearConsole = require('react-dev-utils/clearConsole'); +const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); -var isInteractive = process.stdout.isTTY; -var handleCompile; +const isInteractive = process.stdout.isTTY; +let 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); +const isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1); if (isSmokeTest) { - handleCompile = function (err, stats) { + handleCompile = (err, stats) => { if (err || stats.hasErrors() || stats.hasWarnings()) { process.exit(1); } else { @@ -34,8 +34,9 @@ if (isSmokeTest) { module.exports = function createWebpackCompiler(config, onReadyCallback) { // "Compiler" is a low-level interface to Webpack. // It lets us listen to some events and provide our own custom messages. + let compiler; try { - var compiler = webpack(config, handleCompile); + compiler = webpack(config, handleCompile); } catch (err) { console.log(chalk.red('Failed to compile.')); console.log(); @@ -48,18 +49,18 @@ module.exports = function createWebpackCompiler(config, onReadyCallback) { // recompiling a bundle. WebpackDevServer takes care to pause serving the // 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. - compiler.plugin('invalid', function() { + compiler.plugin('invalid', () => { if (isInteractive) { clearConsole(); } console.log('Compiling...'); }); - var isFirstCompile = true; + let isFirstCompile = true; // "done" event fires when Webpack has finished recompiling the bundle. // Whether or not you have warnings or errors, you will get this event. - compiler.plugin('done', function(stats) { + compiler.plugin('done', (stats) => { if (isInteractive) { clearConsole(); } @@ -67,9 +68,9 @@ module.exports = function createWebpackCompiler(config, onReadyCallback) { // We have switched off the default Webpack output in WebpackDevServer // options so we are going to "massage" the warnings and errors and present // them in a readable focused way. - var messages = formatWebpackMessages(stats.toJson({}, true)); - var isSuccessful = !messages.errors.length && !messages.warnings.length; - var showInstructions = isSuccessful && (isInteractive || isFirstCompile); + const messages = formatWebpackMessages(stats.toJson({}, true)); + const isSuccessful = !messages.errors.length && !messages.warnings.length; + const showInstructions = isSuccessful && (isInteractive || isFirstCompile); if (isSuccessful) { console.log(chalk.green('Compiled successfully!'));