eject.js 5.76 KB
Newer Older
Daniel Grant's avatar
Daniel Grant committed
1
// @remove-file-on-eject
eanplatter's avatar
eanplatter committed
2
3
4
5
6
7
8
9
/**
 * 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.
 */
10
'use strict';
eanplatter's avatar
eanplatter committed
11

12
13
14
15
16
17
18
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');
Daniel Grant's avatar
Daniel Grant committed
19

20
21
const green = chalk.green;
const cyan = chalk.cyan;
eanplatter's avatar
eanplatter committed
22

23
24
25
26
prompt(
  'Are you sure you want to eject? This action is permanent.',
  false
).then(shouldEject => {
Dan Abramov's avatar
Dan Abramov committed
27
  if (!shouldEject) {
28
    console.log(cyan('Close one! Eject aborted.'));
eanplatter's avatar
eanplatter committed
29
30
31
32
    process.exit(1);
  }

  console.log('Ejecting...');
Dan Abramov's avatar
Dan Abramov committed
33

34
35
  const ownPath = paths.ownPath;
  const appPath = paths.appPath;
36
37
38
39

  function verifyAbsent(file) {
    if (fs.existsSync(path.join(appPath, file))) {
      console.error(
40
41
42
43
        `\`${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.'
44
45
46
47
48
      );
      process.exit(1);
    }
  }

49
  const folders = ['config', 'config/jest', 'scripts', 'scripts/utils'];
50

Daniel Grant's avatar
Daniel Grant committed
51
  // Make shallow array of files paths
52
53
54
55
56
57
58
59
60
61
62
63
64
  const files = folders.reduce(
    (files, folder) => {
      return files.concat(
        fs
          .readdirSync(path.join(ownPath, folder))
          // set full path
          .map(file => path.join(ownPath, folder, file))
          // omit dirs from file list
          .filter(file => fs.lstatSync(file).isFile())
      );
    },
    []
  );
eanplatter's avatar
eanplatter committed
65

66
  // Ensure that the app folder is clean and we won't override any files
67
68
  folders.forEach(verifyAbsent);
  files.forEach(verifyAbsent);
eanplatter's avatar
eanplatter committed
69

Daniel Grant's avatar
Daniel Grant committed
70
  console.log();
71
  console.log(cyan(`Copying files into ${appPath}`));
Daniel Grant's avatar
Daniel Grant committed
72

73
74
  folders.forEach(folder => {
    fs.mkdirSync(path.join(appPath, folder));
75
  });
76

77
78
  files.forEach(file => {
    let content = fs.readFileSync(file, 'utf8');
Daniel Grant's avatar
Daniel Grant committed
79
80
81
82
83
84

    // Skip flagged files
    if (content.match(/\/\/ @remove-file-on-eject/)) {
      return;
    }
    content = content
85
      // Remove dead code from .js files on eject
86
87
88
89
      .replace(
        /\/\/ @remove-on-eject-begin([\s\S]*?)\/\/ @remove-on-eject-end/mg,
        ''
      )
90
      // Remove dead code from .applescript files on eject
91
92
93
94
      .replace(
        /-- @remove-on-eject-begin([\s\S]*?)-- @remove-on-eject-end/mg,
        ''
      )
95
      .trim() + '\n';
96
    console.log(`  Adding ${cyan(file.replace(ownPath, ''))} to the project`);
Daniel Grant's avatar
Daniel Grant committed
97
    fs.writeFileSync(file.replace(ownPath, appPath), content);
eanplatter's avatar
eanplatter committed
98
99
100
  });
  console.log();

101
102
  const ownPackage = require(path.join(ownPath, 'package.json'));
  const appPackage = require(path.join(appPath, 'package.json'));
eanplatter's avatar
eanplatter committed
103

Dan Abramov's avatar
Dan Abramov committed
104
  console.log(cyan('Updating the dependencies'));
105
  const ownPackageName = ownPackage.name;
106
  if (appPackage.devDependencies[ownPackageName]) {
107
    console.log(`  Removing ${cyan(ownPackageName)} from devDependencies`);
108
109
110
    delete appPackage.devDependencies[ownPackageName];
  }
  if (appPackage.dependencies[ownPackageName]) {
111
    console.log(`  Removing ${cyan(ownPackageName)} from dependencies`);
112
113
    delete appPackage.dependencies[ownPackageName];
  }
eanplatter's avatar
eanplatter committed
114

115
  Object.keys(ownPackage.dependencies).forEach(key => {
Dan Abramov's avatar
Dan Abramov committed
116
    // For some reason optionalDependencies end up in dependencies after install
117
    if (ownPackage.optionalDependencies[key]) {
Dan Abramov's avatar
Dan Abramov committed
118
119
      return;
    }
120
    console.log(`  Adding ${cyan(key)} to devDependencies`);
121
    appPackage.devDependencies[key] = ownPackage.dependencies[key];
eanplatter's avatar
eanplatter committed
122
  });
123
  console.log();
Dan Abramov's avatar
Dan Abramov committed
124
  console.log(cyan('Updating the scripts'));
Dan Abramov's avatar
Dan Abramov committed
125
  delete appPackage.scripts['eject'];
126
127
128
129
130
131
132
  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'
      );
133
      console.log(
134
        `  Replacing ${cyan(`"${binKey} ${key}"`)} with ${cyan(`"node scripts/${key}.js"`)}`
135
136
      );
    });
eanplatter's avatar
eanplatter committed
137
138
  });

139
  console.log();
Dan Abramov's avatar
Dan Abramov committed
140
  console.log(cyan('Configuring package.json'));
Dan Abramov's avatar
Dan Abramov committed
141
  // Add Jest config
142
  console.log(`  Adding ${cyan('Jest')} configuration`);
Christoph Pojer's avatar
Christoph Pojer committed
143
  appPackage.jest = createJestConfig(
144
    filePath => path.posix.join('<rootDir>', filePath),
145
146
    null,
    true
Christoph Pojer's avatar
Christoph Pojer committed
147
148
  );

149
  // Add Babel config
150
  console.log(`  Adding ${cyan('Babel')} preset`);
151
152
153
  appPackage.babel = {
    presets: ['react-app'],
  };
154
155

  // Add ESlint config
156
  console.log(`  Adding ${cyan('ESLint')} configuration`);
157
158
159
  appPackage.eslintConfig = {
    extends: 'react-app',
  };
160

eanplatter's avatar
eanplatter committed
161
  fs.writeFileSync(
162
    path.join(appPath, 'package.json'),
163
    JSON.stringify(appPackage, null, 2) + '\n'
eanplatter's avatar
eanplatter committed
164
165
166
  );
  console.log();

167
168
169
170
  // "Don't destroy what isn't ours"
  if (ownPath.indexOf(appPath) === 0) {
    try {
      // remove react-scripts and react-scripts binaries from app node_modules
171
      Object.keys(ownPackage.bin).forEach(binKey => {
172
173
174
        fs.removeSync(path.join(appPath, 'node_modules', '.bin', binKey));
      });
      fs.removeSync(ownPath);
175
    } catch (e) {
176
177
      // It's not essential that this succeeds
    }
178
  }
179

180
  if (fs.existsSync(paths.yarnLockFile)) {
Ville Immonen's avatar
Ville Immonen committed
181
    console.log(cyan('Running yarn...'));
182
    spawnSync('yarnpkg', [], { stdio: 'inherit' });
Ville Immonen's avatar
Ville Immonen committed
183
184
  } else {
    console.log(cyan('Running npm install...'));
185
    spawnSync('npm', ['install'], { stdio: 'inherit' });
Ville Immonen's avatar
Ville Immonen committed
186
  }
187
  console.log(green('Ejected successfully!'));
eanplatter's avatar
eanplatter committed
188
189
  console.log();

190
191
  console.log(green('Please consider sharing why you ejected in this survey:'));
  console.log(green('  http://goo.gl/forms/Bi6CZjk1EqsdelXk1'));
192
193
  console.log();
});