UNPKG

2.51 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2015-present, Facebook, Inc.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7'use strict';
8
9const browserslist = require('browserslist');
10const chalk = require('chalk');
11const os = require('os');
12const prompts = require('prompts');
13const pkgUp = require('pkg-up');
14const fs = require('fs');
15
16const defaultBrowsers = {
17 production: ['>0.2%', 'not dead', 'not op_mini all'],
18 development: [
19 'last 1 chrome version',
20 'last 1 firefox version',
21 'last 1 safari version',
22 ],
23};
24
25function shouldSetBrowsers(isInteractive) {
26 if (!isInteractive) {
27 return Promise.resolve(true);
28 }
29
30 const question = {
31 type: 'confirm',
32 name: 'shouldSetBrowsers',
33 message:
34 chalk.yellow("We're unable to detect target browsers.") +
35 `\n\nWould you like to add the defaults to your ${chalk.bold(
36 'package.json'
37 )}?`,
38 initial: true,
39 };
40
41 return prompts(question).then(answer => answer.shouldSetBrowsers);
42}
43
44function checkBrowsers(dir, isInteractive, retry = true) {
45 const current = browserslist.loadConfig({ path: dir });
46 if (current != null) {
47 return Promise.resolve(current);
48 }
49
50 if (!retry) {
51 return Promise.reject(
52 new Error(
53 chalk.red(
54 'As of react-scripts >=2 you must specify targeted browsers.'
55 ) +
56 os.EOL +
57 `Please add a ${chalk.underline(
58 'browserslist'
59 )} key to your ${chalk.bold('package.json')}.`
60 )
61 );
62 }
63
64 return shouldSetBrowsers(isInteractive).then(shouldSetBrowsers => {
65 if (!shouldSetBrowsers) {
66 return checkBrowsers(dir, isInteractive, false);
67 }
68
69 return (
70 pkgUp({ cwd: dir })
71 .then(filePath => {
72 if (filePath == null) {
73 return Promise.reject();
74 }
75 const pkg = JSON.parse(fs.readFileSync(filePath));
76 pkg['browserslist'] = defaultBrowsers;
77 fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2) + os.EOL);
78
79 browserslist.clearCaches();
80 console.log();
81 console.log(
82 `${chalk.green('Set target browsers:')} ${chalk.cyan(
83 defaultBrowsers.join(', ')
84 )}`
85 );
86 console.log();
87 })
88 // Swallow any error
89 .catch(() => {})
90 .then(() => checkBrowsers(dir, isInteractive, false))
91 );
92 });
93}
94
95module.exports = { defaultBrowsers, checkBrowsers };