create.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const fs = require('fs-extra')
  2. const path = require('path')
  3. const inquirer = require('inquirer')
  4. const Creator = require('./Creator')
  5. const { clearConsole } = require('./util/clearConsole')
  6. const { getPromptModules } = require('./util/createTools')
  7. const { chalk, error, stopSpinner, exit } = require('@vue/cli-shared-utils')
  8. const validateProjectName = require('validate-npm-package-name')
  9. async function create (projectName, options) {
  10. if (options.proxy) {
  11. process.env.HTTP_PROXY = options.proxy
  12. }
  13. const cwd = options.cwd || process.cwd()
  14. const inCurrent = projectName === '.'
  15. const name = inCurrent ? path.relative('../', cwd) : projectName
  16. const targetDir = path.resolve(cwd, projectName || '.')
  17. const result = validateProjectName(name)
  18. if (!result.validForNewPackages) {
  19. console.error(chalk.red(`Invalid project name: "${name}"`))
  20. result.errors && result.errors.forEach(err => {
  21. console.error(chalk.red.dim('Error: ' + err))
  22. })
  23. result.warnings && result.warnings.forEach(warn => {
  24. console.error(chalk.red.dim('Warning: ' + warn))
  25. })
  26. exit(1)
  27. }
  28. if (fs.existsSync(targetDir) && !options.merge) {
  29. if (options.force) {
  30. await fs.remove(targetDir)
  31. } else {
  32. await clearConsole()
  33. if (inCurrent) {
  34. const { ok } = await inquirer.prompt([
  35. {
  36. name: 'ok',
  37. type: 'confirm',
  38. message: `Generate project in current directory?`
  39. }
  40. ])
  41. if (!ok) {
  42. return
  43. }
  44. } else {
  45. const { action } = await inquirer.prompt([
  46. {
  47. name: 'action',
  48. type: 'list',
  49. message: `Target directory ${chalk.cyan(targetDir)} already exists. Pick an action:`,
  50. choices: [
  51. { name: 'Overwrite', value: 'overwrite' },
  52. { name: 'Merge', value: 'merge' },
  53. { name: 'Cancel', value: false }
  54. ]
  55. }
  56. ])
  57. if (!action) {
  58. return
  59. } else if (action === 'overwrite') {
  60. console.log(`\nRemoving ${chalk.cyan(targetDir)}...`)
  61. await fs.remove(targetDir)
  62. }
  63. }
  64. }
  65. }
  66. const creator = new Creator(name, targetDir, getPromptModules())
  67. await creator.create(options)
  68. }
  69. module.exports = (...args) => {
  70. return create(...args).catch(err => {
  71. stopSpinner(false) // do not persist
  72. error(err)
  73. if (!process.env.VUE_CLI_TEST) {
  74. process.exit(1)
  75. }
  76. })
  77. }