browsersHelper.js 2.4 KB

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