browsersHelper.js 2.13 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

const browserslist = require('browserslist');
const chalk = require('chalk');
const os = require('os');
12
13
14
const inquirer = require('inquirer');
const pkgUp = require('pkg-up');
const fs = require('fs');
15

16
const defaultBrowsers = ['>0.25%', 'not op_mini all', 'ie 11'];
17

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function checkBrowsers(dir, retry = true) {
  const current = browserslist.findConfig(dir);
  if (current != null) {
    return Promise.resolve(current);
  }

  if (!retry) {
    return Promise.reject(
      new Error(
        chalk.red(
          'As of react-scripts >=2 you must specify targeted browsers.'
        ) +
          os.EOL +
          `Please add a ${chalk.underline(
            'browserslist'
          )} key to your ${chalk.bold('package.json')}.`
      )
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

  const question = {
    type: 'confirm',
    name: 'shouldSetBrowsers',
    message:
      chalk.yellow("We're unable to detect target browsers.") +
      `\n\nWould you like to add the defaults to your ${chalk.bold(
        'package.json'
      )}?`,
    default: true,
  };
  return inquirer.prompt(question).then(answer => {
    if (answer.shouldSetBrowsers) {
      return (
        pkgUp(dir)
          .then(filePath => {
            if (filePath == null) {
              return Promise.reject();
            }
            const pkg = JSON.parse(fs.readFileSync(filePath));
            pkg['browserslist'] = defaultBrowsers;
            fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2) + os.EOL);

            browserslist.clearCaches();
            console.log();
62
63
64
65
66
            console.log(
              `${chalk.green('Set target browsers:')} ${chalk.cyan(
                defaultBrowsers.join(', ')
              )}`
            );
67
68
69
70
71
72
73
74
75
76
            console.log();
          })
          // Swallow any error
          .catch(() => {})
          .then(() => checkBrowsers(dir, false))
      );
    } else {
      return checkBrowsers(dir, false);
    }
  });
77
78
}

79
module.exports = { defaultBrowsers, checkBrowsers };