add.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const invoke = require('./invoke')
  2. const inquirer = require('inquirer')
  3. const {
  4. chalk,
  5. semver,
  6. resolveModule,
  7. loadModule
  8. } = require('@vue/cli-shared-utils')
  9. const getVersions = require('./util/getVersions')
  10. const PackageManager = require('./util/ProjectPackageManager')
  11. const {
  12. log,
  13. error,
  14. resolvePluginId,
  15. isOfficialPlugin
  16. } = require('@vue/cli-shared-utils')
  17. const confirmIfGitDirty = require('./util/confirmIfGitDirty')
  18. async function add (pluginName, options = {}, context = process.cwd()) {
  19. if (!(await confirmIfGitDirty(context))) {
  20. return
  21. }
  22. // for `vue add` command in 3.x projects
  23. const servicePkg = loadModule('@vue/cli-service/package.json', context)
  24. if (servicePkg && semver.satisfies(servicePkg.version, '3.x')) {
  25. // special internal "plugins"
  26. if (/^(@vue\/)?router$/.test(pluginName)) {
  27. return addRouter(context)
  28. }
  29. if (/^(@vue\/)?vuex$/.test(pluginName)) {
  30. return addVuex(context)
  31. }
  32. }
  33. const packageName = resolvePluginId(pluginName)
  34. log()
  35. log(`📦 Installing ${chalk.cyan(packageName)}...`)
  36. log()
  37. const pm = new PackageManager({ context })
  38. const { latestMinor } = await getVersions()
  39. if (isOfficialPlugin(packageName)) {
  40. await pm.add(`${packageName}@~${latestMinor}`)
  41. } else {
  42. await pm.add(packageName, { tilde: true })
  43. }
  44. log(`${chalk.green('✔')} Successfully installed plugin: ${chalk.cyan(packageName)}`)
  45. log()
  46. const generatorPath = resolveModule(`${packageName}/generator`, context)
  47. if (generatorPath) {
  48. invoke(pluginName, options, context)
  49. } else {
  50. log(`Plugin ${packageName} does not have a generator to invoke`)
  51. }
  52. }
  53. module.exports = (...args) => {
  54. return add(...args).catch(err => {
  55. error(err)
  56. if (!process.env.VUE_CLI_TEST) {
  57. process.exit(1)
  58. }
  59. })
  60. }
  61. async function addRouter (context) {
  62. const options = await inquirer.prompt([{
  63. name: 'routerHistoryMode',
  64. type: 'confirm',
  65. message: `Use history mode for router? ${chalk.yellow(`(Requires proper server setup for index fallback in production)`)}`
  66. }])
  67. invoke.runGenerator(context, {
  68. id: 'core:router',
  69. apply: loadModule('@vue/cli-service/generator/router', context),
  70. options
  71. })
  72. }
  73. async function addVuex (context) {
  74. invoke.runGenerator(context, {
  75. id: 'core:vuex',
  76. apply: loadModule('@vue/cli-service/generator/vuex', context)
  77. })
  78. }