From 2df317724d166d55156c915e6a187f32655c19e2 Mon Sep 17 00:00:00 2001 From: Johann Hubert Sonntagbauer Date: Tue, 28 Feb 2017 14:45:41 +0100 Subject: [PATCH] fix react dependency versions during initial install (#1669) * fix react dependency versions during initial install * add review remarks --- packages/create-react-app/index.js | 32 +++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/packages/create-react-app/index.js b/packages/create-react-app/index.js index d5afee43b8f..bb1fab6fdec 100755 --- a/packages/create-react-app/index.js +++ b/packages/create-react-app/index.js @@ -212,8 +212,9 @@ function run(root, appName, version, verbose, originalDirectory, template) { checkNodeVersion(packageName); // Since react-scripts has been installed with --save - // We need to move it into devDependencies and rewrite package.json - moveReactScriptsToDev(packageName); + // we need to move it into devDependencies and rewrite package.json + // also ensure react dependencies have caret version range + fixDependencies(packageName); var scriptsPath = path.resolve( process.cwd(), @@ -325,7 +326,29 @@ function checkAppName(appName) { } } -function moveReactScriptsToDev(packageName) { +function makeCaretRange(dependencies, name) { + var version = dependencies[name]; + + if (typeof version === 'undefined') { + console.error( + chalk.red('Missing ' + name + ' dependency in package.json') + ); + process.exit(1); + } + + var 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) + ); + patchedVersion = version; + } + + dependencies[name] = patchedVersion; +} + +function fixDependencies(packageName) { var packagePath = path.join(process.cwd(), 'package.json'); var packageJson = require(packagePath); @@ -349,6 +372,9 @@ function moveReactScriptsToDev(packageName) { packageJson.devDependencies[packageName] = packageVersion; delete packageJson.dependencies[packageName]; + makeCaretRange(packageJson.dependencies, 'react'); + makeCaretRange(packageJson.dependencies, 'react-dom'); + fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2)); }