init.js 5.89 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 spawn = require('react-dev-utils/crossSpawn');
21
22
23
24
25
26
27
28

module.exports = function(
  appPath,
  appName,
  verbose,
  originalDirectory,
  template
) {
29
30
  const ownPackageName = require(path.join(__dirname, '..', 'package.json'))
    .name;
31
32
33
  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
34

Dan Abramov's avatar
Dan Abramov committed
35
  // Copy over some of the devDependencies
36
  appPackage.dependencies = appPackage.dependencies || {};
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
37
38

  // Setup the script rules
Dan Abramov's avatar
Dan Abramov committed
39
  appPackage.scripts = {
40
41
42
43
    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
44
  };
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
45

46
47
48
49
50
51
  appPackage.browserslist = {
    development: ['chrome', 'firefox', 'edge'].map(
      browser => `last 2 ${browser} versions`
    ),
    production: ['>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 11'],
  };
52

Dan Abramov's avatar
Dan Abramov committed
53
  fs.writeFileSync(
54
55
    path.join(appPath, 'package.json'),
    JSON.stringify(appPackage, null, 2)
Dan Abramov's avatar
Dan Abramov committed
56
  );
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
57

58
  const readmeExists = fs.existsSync(path.join(appPath, 'README.md'));
59
  if (readmeExists) {
60
61
62
63
    fs.renameSync(
      path.join(appPath, 'README.md'),
      path.join(appPath, 'README.old.md')
    );
64
65
  }

66
  // Copy the files for the user
67
68
69
  const templatePath = template
    ? path.resolve(originalDirectory, template)
    : path.join(ownPath, 'template');
70
71
72
  if (fs.existsSync(templatePath)) {
    fs.copySync(templatePath, appPath);
  } else {
73
74
75
    console.error(
      `Could not locate supplied template: ${chalk.green(templatePath)}`
    );
76
77
    return;
  }
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
78

79
80
  // Rename gitignore after the fact to prevent npm from renaming it to .npmignore
  // See: https://github.com/npm/npm/issues/1862
81
82
83
84
85
86
87
88
89
90
91
92
93
94
  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;
        }
95
96
      }
    }
97
  );
98

99
100
  let command;
  let args;
Ville Immonen's avatar
Ville Immonen committed
101
102

  if (useYarn) {
103
    command = 'yarnpkg';
Ville Immonen's avatar
Ville Immonen committed
104
105
106
    args = ['add'];
  } else {
    command = 'npm';
107
    args = ['install', '--save', verbose && '--verbose'].filter(e => e);
Ville Immonen's avatar
Ville Immonen committed
108
109
110
  }
  args.push('react', 'react-dom');

111
  // Install additional template dependencies, if present
112
113
114
115
  const templateDependenciesPath = path.join(
    appPath,
    '.template.dependencies.json'
  );
116
  if (fs.existsSync(templateDependenciesPath)) {
117
118
119
120
121
122
    const templateDependencies = require(templateDependenciesPath).dependencies;
    args = args.concat(
      Object.keys(templateDependencies).map(key => {
        return `${key}@${templateDependencies[key]}`;
      })
    );
123
124
125
    fs.unlinkSync(templateDependenciesPath);
  }

126
127
128
129
  // 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) {
130
    console.log(`Installing react and react-dom using ${command}...`);
131
    console.log();
Ville Immonen's avatar
Ville Immonen committed
132

133
    const proc = spawn.sync(command, args, { stdio: 'inherit' });
134
    if (proc.status !== 0) {
135
      console.error(`\`${command} ${args.join(' ')}\` failed`);
136
137
      return;
    }
138
  }
139

140
141
142
  // Display the most elegant way to cd.
  // This needs to handle an undefined originalDirectory for
  // backward compatibility with old global-cli's.
143
144
  let cdpath;
  if (originalDirectory && path.join(originalDirectory, appName) === appPath) {
145
146
147
148
    cdpath = appName;
  } else {
    cdpath = appPath;
  }
Kevin Lacker's avatar
Kevin Lacker committed
149

150
  // Change displayed command to yarn instead of yarnpkg
151
  const displayedCommand = useYarn ? 'yarn' : 'npm';
152

153
  console.log();
154
  console.log(`Success! Created ${appName} at ${appPath}`);
155
156
  console.log('Inside that directory, you can run several commands:');
  console.log();
157
  console.log(chalk.cyan(`  ${displayedCommand} start`));
158
159
  console.log('    Starts the development server.');
  console.log();
160
161
162
  console.log(
    chalk.cyan(`  ${displayedCommand} ${useYarn ? '' : 'run '}build`)
  );
163
164
  console.log('    Bundles the app into static files for production.');
  console.log();
165
  console.log(chalk.cyan(`  ${displayedCommand} test`));
166
167
  console.log('    Starts the test runner.');
  console.log();
168
169
170
  console.log(
    chalk.cyan(`  ${displayedCommand} ${useYarn ? '' : 'run '}eject`)
  );
171
172
173
174
175
176
  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!'
  );
177
178
179
180
  console.log();
  console.log('We suggest that you begin by typing:');
  console.log();
  console.log(chalk.cyan('  cd'), cdpath);
181
  console.log(`  ${chalk.cyan(`${displayedCommand} start`)}`);
182
  if (readmeExists) {
183
    console.log();
184
185
186
187
188
    console.log(
      chalk.yellow(
        'You had a `README.md` file, we renamed it to `README.old.md`'
      )
    );
189
190
191
  }
  console.log();
  console.log('Happy hacking!');
192
};
193
194

function isReactInstalled(appPackage) {
195
  const dependencies = appPackage.dependencies || {};
196

197
198
199
200
  return (
    typeof dependencies.react !== 'undefined' &&
    typeof dependencies['react-dom'] !== 'undefined'
  );
201
}