index.js 6.09 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
#!/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.
 */

Christopher Chedeau's avatar
Christopher Chedeau committed
12
13
14
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
15
16
17
18
19
20
21
22
23
//
// 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.
//
Christopher Chedeau's avatar
Christopher Chedeau committed
24
// If you need to add a new command, please add it to the scripts/ folder.
25
26
//
// The only reason to modify this file is to add more warnings and
Christopher Chedeau's avatar
Christopher Chedeau committed
27
// troubleshooting information for the `create-react-app` command.
28
29
30
31
//
// Do not make breaking changes! We absolutely don't want to have to
// tell people to update their global version of create-react-app.
//
Christopher Chedeau's avatar
Christopher Chedeau committed
32
33
34
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
35
36
37
38
39

'use strict';

var fs = require('fs');
var path = require('path');
40
var spawn = require('cross-spawn');
41
42
var chalk = require('chalk');
var semver = require('semver');
Christopher Chedeau's avatar
Christopher Chedeau committed
43
var argv = require('minimist')(process.argv.slice(2));
44
var pathExists = require('path-exists');
Christopher Chedeau's avatar
Christopher Chedeau committed
45

46
/**
Christopher Chedeau's avatar
Christopher Chedeau committed
47
48
 * Arguments:
 *   --version - to print current version
49
 *   --verbose - to print logs while init
Christopher Chedeau's avatar
Christopher Chedeau committed
50
51
52
 *   --scripts-version <alternative package>
 *     Example of valid values:
 *     - a specific npm version: "0.22.0-rc1"
53
 *     - a .tgz archive from any npm repo: "https://registry.npmjs.org/react-scripts/-/react-scripts-0.20.0.tgz"
54
 *     - a package prepared with `tasks/clean_pack.sh`: "/Users/home/vjeux/create-react-app/react-scripts-0.22.0.tgz"
55
56
57
 */
var commands = argv._;
if (commands.length === 0) {
Max Stoiber's avatar
Max Stoiber committed
58
59
60
61
  if (argv.version) {
    console.log('create-react-app version: ' + require('./package.json').version);
    process.exit();
  }
62
  console.error(
Kevin Lacker's avatar
Kevin Lacker committed
63
    'Usage: create-react-app <project-directory> [--verbose]'
64
65
66
67
68
69
70
  );
  process.exit(1);
}

createApp(commands[0], argv.verbose, argv['scripts-version']);

function createApp(name, verbose, version) {
71
  var root = path.resolve(name);
72
73
74
75
  var appName = path.basename(root);

  checkAppName(appName);

76
77
  if (!pathExists.sync(name)) {
    fs.mkdirSync(root);
Dennis Ushakov's avatar
Dennis Ushakov committed
78
  } else if (!isSafeToCreateProjectIn(root)) {
79
    console.log('The directory `' + name + '` contains file(s) that could conflict. Aborting.');
Christopher Chedeau's avatar
Christopher Chedeau committed
80
    process.exit(1);
81
82
83
  }

  console.log(
84
    'Creating a new React app in ' + root + '.'
85
  );
86
  console.log();
87
88
89

  var packageJson = {
    name: appName,
90
    version: '0.1.0',
91
92
    private: true,
  };
Christoph Pojer's avatar
Christoph Pojer committed
93
94
95
96
  fs.writeFileSync(
    path.join(root, 'package.json'),
    JSON.stringify(packageJson, null, 2)
  );
Kevin Lacker's avatar
Kevin Lacker committed
97
  var originalDirectory = process.cwd();
98
99
  process.chdir(root);

Dan Abramov's avatar
Dan Abramov committed
100
  console.log('Installing packages. This might take a couple minutes.');
Kevin Lacker's avatar
Kevin Lacker committed
101
  console.log('Installing react-scripts from npm...');
102
  console.log();
103

Kevin Lacker's avatar
Kevin Lacker committed
104
  run(root, appName, version, verbose, originalDirectory);
105
106
}

Kevin Lacker's avatar
Kevin Lacker committed
107
function run(root, appName, version, verbose, originalDirectory) {
108
109
110
  var args = [
    'install',
    verbose && '--verbose',
111
    '--save-dev',
112
113
114
115
116
117
118
119
120
121
    '--save-exact',
    getInstallPackage(version),
  ].filter(function(e) { return e; });
  var proc = spawn('npm', args, {stdio: 'inherit'});
  proc.on('close', function (code) {
    if (code !== 0) {
      console.error('`npm ' + args.join(' ') + '` failed');
      return;
    }

122
123
    checkNodeVersion();

124
125
126
    var scriptsPath = path.resolve(
      process.cwd(),
      'node_modules',
127
      'react-scripts',
128
      'scripts',
129
130
131
      'init.js'
    );
    var init = require(scriptsPath);
Kevin Lacker's avatar
Kevin Lacker committed
132
    init(root, appName, verbose, originalDirectory);
133
134
135
136
  });
}

function getInstallPackage(version) {
137
  var packageToInstall = 'react-scripts';
138
139
140
141
142
143
144
145
146
147
148
149
150
151
  var validSemver = semver.valid(version);
  if (validSemver) {
    packageToInstall += '@' + validSemver;
  } else if (version) {
    // for tar.gz or alternative paths
    packageToInstall = version;
  }
  return packageToInstall;
}

function checkNodeVersion() {
  var packageJsonPath = path.resolve(
    process.cwd(),
    'node_modules',
152
    'react-scripts',
153
154
155
156
157
158
    'package.json'
  );
  var packageJson = require(packageJsonPath);
  if (!packageJson.engines || !packageJson.engines.node) {
    return;
  }
Christopher Chedeau's avatar
Christopher Chedeau committed
159

160
161
162
  if (!semver.satisfies(process.version, packageJson.engines.node)) {
    console.error(
      chalk.red(
Christopher Chedeau's avatar
Christopher Chedeau committed
163
164
        'You are currently running Node %s but create-react-app requires %s.' +
        ' Please use a supported version of Node.\n'
165
166
167
168
      ),
      process.version,
      packageJson.engines.node
    );
169
    process.exit(1);
170
171
  }
}
172

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
function checkAppName(appName) {
  // 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();

  if (allDependencies.indexOf(appName) >= 0) {
    console.error(
      chalk.red(
        `Can't use "${appName}" as the app name because a dependency with the same name exists.\n\n` +
        `Following names ${chalk.red.bold('must not')} be used:\n\n`
      )

      +

      chalk.cyan(
        allDependencies.map(depName => `  ${depName}`).join('\n')
      )
    );
    process.exit(1);
  }
}

Dennis Ushakov's avatar
Dennis Ushakov committed
196
197
198
199
// If project only contains files generated by GH, it’s safe.
// 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) {
200
  var validFiles = [
Dennis Ushakov's avatar
Dennis Ushakov committed
201
    '.DS_Store', 'Thumbs.db', '.git', '.gitignore', '.idea', 'README.md', 'LICENSE'
202
203
204
205
206
207
  ];
  return fs.readdirSync(root)
    .every(function(file) {
      return validFiles.indexOf(file) >= 0;
    });
}