init.js 6.69 KB
Newer Older
Daniel Grant's avatar
Daniel Grant committed
1
// @remove-file-on-eject
Christopher Chedeau's avatar
Christopher Chedeau committed
2
3
4
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
Sophie Alpert's avatar
Sophie Alpert committed
5
6
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
Christopher Chedeau's avatar
Christopher Chedeau committed
7
 */
8
9
'use strict';

10
11
12
13
14
15
16
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
  throw err;
});

17
18
19
const fs = require('fs-extra');
const path = require('path');
const chalk = require('chalk');
20
const execSync = require('child_process').execSync;
21
const spawn = require('react-dev-utils/crossSpawn');
22
23
const { defaultBrowsers } = require('react-dev-utils/browsersHelper');
const os = require('os');
24

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
function insideGitRepository() {
  try {
    execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
    return true;
  } catch (e) {
    return false;
  }
}

function insideMercurialRepository() {
  try {
    execSync('hg --cwd . root', { stdio: 'ignore' });
    return true;
  } catch (e) {
    return false;
  }
}

function gitInit() {
  try {
    execSync('git --version', { stdio: 'ignore' });

    if (insideGitRepository() || insideMercurialRepository()) {
      return false;
    }

    execSync('git init', { stdio: 'ignore' });
    execSync('git add -A', { stdio: 'ignore' });
    execSync('git commit -m "Initial commit from Create React App"', {
      stdio: 'ignore',
    });

    return true;
  } catch (e) {
    return false;
  }
}

63
64
65
66
67
68
69
module.exports = function(
  appPath,
  appName,
  verbose,
  originalDirectory,
  template
) {
70
71
  const ownPackageName = require(path.join(__dirname, '..', 'package.json'))
    .name;
72
73
74
  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'));
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
75

Dan Abramov's avatar
Dan Abramov committed
76
  // Copy over some of the devDependencies
77
  appPackage.dependencies = appPackage.dependencies || {};
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
78
79

  // Setup the script rules
Dan Abramov's avatar
Dan Abramov committed
80
  appPackage.scripts = {
81
82
83
84
    start: 'react-scripts start',
    build: 'react-scripts build',
    test: 'react-scripts test --env=jsdom',
    eject: 'react-scripts eject',
Dan Abramov's avatar
Dan Abramov committed
85
  };
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
86

87
  appPackage.browserslist = defaultBrowsers;
88

Dan Abramov's avatar
Dan Abramov committed
89
  fs.writeFileSync(
90
    path.join(appPath, 'package.json'),
91
    JSON.stringify(appPackage, null, 2) + os.EOL
Dan Abramov's avatar
Dan Abramov committed
92
  );
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
93

94
  const readmeExists = fs.existsSync(path.join(appPath, 'README.md'));
95
  if (readmeExists) {
96
97
98
99
    fs.renameSync(
      path.join(appPath, 'README.md'),
      path.join(appPath, 'README.old.md')
    );
100
101
  }

102
  // Copy the files for the user
103
104
105
  const templatePath = template
    ? path.resolve(originalDirectory, template)
    : path.join(ownPath, 'template');
106
107
108
  if (fs.existsSync(templatePath)) {
    fs.copySync(templatePath, appPath);
  } else {
109
110
111
    console.error(
      `Could not locate supplied template: ${chalk.green(templatePath)}`
    );
112
113
    return;
  }
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
114

115
116
  // Rename gitignore after the fact to prevent npm from renaming it to .npmignore
  // See: https://github.com/npm/npm/issues/1862
117
118
119
120
121
122
123
124
125
126
127
128
129
130
  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') {
          const data = fs.readFileSync(path.join(appPath, 'gitignore'));
          fs.appendFileSync(path.join(appPath, '.gitignore'), data);
          fs.unlinkSync(path.join(appPath, 'gitignore'));
        } else {
          throw err;
        }
131
132
      }
    }
133
  );
134

135
136
  let command;
  let args;
Ville Immonen's avatar
Ville Immonen committed
137
138

  if (useYarn) {
139
    command = 'yarnpkg';
Ville Immonen's avatar
Ville Immonen committed
140
141
142
    args = ['add'];
  } else {
    command = 'npm';
143
    args = ['install', '--save', verbose && '--verbose'].filter(e => e);
Ville Immonen's avatar
Ville Immonen committed
144
145
146
  }
  args.push('react', 'react-dom');

147
  // Install additional template dependencies, if present
148
149
150
151
  const templateDependenciesPath = path.join(
    appPath,
    '.template.dependencies.json'
  );
152
  if (fs.existsSync(templateDependenciesPath)) {
153
154
155
156
157
158
    const templateDependencies = require(templateDependenciesPath).dependencies;
    args = args.concat(
      Object.keys(templateDependencies).map(key => {
        return `${key}@${templateDependencies[key]}`;
      })
    );
159
160
161
    fs.unlinkSync(templateDependenciesPath);
  }

162
163
164
165
  // Install react and react-dom for backward compatibility with old CRA cli
  // which doesn't install react and react-dom along with react-scripts
  // or template is presetend (via --internal-testing-template)
  if (!isReactInstalled(appPackage) || template) {
166
    console.log(`Installing react and react-dom using ${command}...`);
167
    console.log();
Ville Immonen's avatar
Ville Immonen committed
168

169
    const proc = spawn.sync(command, args, { stdio: 'inherit' });
170
    if (proc.status !== 0) {
171
      console.error(`\`${command} ${args.join(' ')}\` failed`);
172
173
      return;
    }
174
  }
175

176
177
178
179
  if (gitInit()) {
    console.log('Initialized git repository');
  }

180
181
182
  // Display the most elegant way to cd.
  // This needs to handle an undefined originalDirectory for
  // backward compatibility with old global-cli's.
183
184
  let cdpath;
  if (originalDirectory && path.join(originalDirectory, appName) === appPath) {
185
186
187
188
    cdpath = appName;
  } else {
    cdpath = appPath;
  }
Kevin Lacker's avatar
Kevin Lacker committed
189

190
  // Change displayed command to yarn instead of yarnpkg
191
  const displayedCommand = useYarn ? 'yarn' : 'npm';
192

193
  console.log();
194
  console.log(`Success! Created ${appName} at ${appPath}`);
195
196
  console.log('Inside that directory, you can run several commands:');
  console.log();
197
  console.log(chalk.cyan(`  ${displayedCommand} start`));
198
199
  console.log('    Starts the development server.');
  console.log();
200
201
202
  console.log(
    chalk.cyan(`  ${displayedCommand} ${useYarn ? '' : 'run '}build`)
  );
203
204
  console.log('    Bundles the app into static files for production.');
  console.log();
205
  console.log(chalk.cyan(`  ${displayedCommand} test`));
206
207
  console.log('    Starts the test runner.');
  console.log();
208
209
210
  console.log(
    chalk.cyan(`  ${displayedCommand} ${useYarn ? '' : 'run '}eject`)
  );
211
212
213
214
215
216
  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!'
  );
217
218
219
220
  console.log();
  console.log('We suggest that you begin by typing:');
  console.log();
  console.log(chalk.cyan('  cd'), cdpath);
221
  console.log(`  ${chalk.cyan(`${displayedCommand} start`)}`);
222
  if (readmeExists) {
223
    console.log();
224
225
226
227
228
    console.log(
      chalk.yellow(
        'You had a `README.md` file, we renamed it to `README.old.md`'
      )
    );
229
230
231
  }
  console.log();
  console.log('Happy hacking!');
232
};
233
234

function isReactInstalled(appPackage) {
235
  const dependencies = appPackage.dependencies || {};
236

237
238
239
240
  return (
    typeof dependencies.react !== 'undefined' &&
    typeof dependencies['react-dom'] !== 'undefined'
  );
241
}