Creator.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. const path = require('path')
  2. const debug = require('debug')
  3. const inquirer = require('inquirer')
  4. const EventEmitter = require('events')
  5. const Generator = require('./Generator')
  6. const cloneDeep = require('lodash.clonedeep')
  7. const sortObject = require('./util/sortObject')
  8. const getVersions = require('./util/getVersions')
  9. const PackageManager = require('./util/ProjectPackageManager')
  10. const { clearConsole } = require('./util/clearConsole')
  11. const PromptModuleAPI = require('./PromptModuleAPI')
  12. const writeFileTree = require('./util/writeFileTree')
  13. const { formatFeatures } = require('./util/features')
  14. const loadLocalPreset = require('./util/loadLocalPreset')
  15. const loadRemotePreset = require('./util/loadRemotePreset')
  16. const generateReadme = require('./util/generateReadme')
  17. const { resolvePkg } = require('@vue/cli-shared-utils')
  18. const {
  19. defaults,
  20. saveOptions,
  21. loadOptions,
  22. savePreset,
  23. validatePreset
  24. } = require('./options')
  25. const {
  26. chalk,
  27. execa,
  28. log,
  29. warn,
  30. error,
  31. logWithSpinner,
  32. stopSpinner,
  33. hasGit,
  34. hasProjectGit,
  35. hasYarn,
  36. hasPnpm3OrLater,
  37. hasPnpmVersionOrLater,
  38. exit,
  39. loadModule
  40. } = require('@vue/cli-shared-utils')
  41. const isManualMode = answers => answers.preset === '__manual__'
  42. module.exports = class Creator extends EventEmitter {
  43. constructor (name, context, promptModules) {
  44. super()
  45. this.name = name
  46. this.context = process.env.VUE_CLI_CONTEXT = context
  47. const { presetPrompt, featurePrompt } = this.resolveIntroPrompts()
  48. this.presetPrompt = presetPrompt
  49. this.featurePrompt = featurePrompt
  50. this.outroPrompts = this.resolveOutroPrompts()
  51. this.injectedPrompts = []
  52. this.promptCompleteCbs = []
  53. this.afterInvokeCbs = []
  54. this.afterAnyInvokeCbs = []
  55. this.run = this.run.bind(this)
  56. const promptAPI = new PromptModuleAPI(this)
  57. promptModules.forEach(m => m(promptAPI))
  58. }
  59. async create (cliOptions = {}, preset = null) {
  60. const isTestOrDebug = process.env.VUE_CLI_TEST || process.env.VUE_CLI_DEBUG
  61. const { run, name, context, afterInvokeCbs, afterAnyInvokeCbs } = this
  62. if (!preset) {
  63. if (cliOptions.preset) {
  64. // vue create foo --preset bar
  65. preset = await this.resolvePreset(cliOptions.preset, cliOptions.clone)
  66. } else if (cliOptions.default) {
  67. // vue create foo --default
  68. preset = defaults.presets.default
  69. } else if (cliOptions.inlinePreset) {
  70. // vue create foo --inlinePreset {...}
  71. try {
  72. preset = JSON.parse(cliOptions.inlinePreset)
  73. } catch (e) {
  74. error(`CLI inline preset is not valid JSON: ${cliOptions.inlinePreset}`)
  75. exit(1)
  76. }
  77. } else {
  78. preset = await this.promptAndResolvePreset()
  79. }
  80. }
  81. // clone before mutating
  82. preset = cloneDeep(preset)
  83. // inject core service
  84. preset.plugins['@vue/cli-service'] = Object.assign({
  85. projectName: name
  86. }, preset)
  87. if (cliOptions.bare) {
  88. preset.plugins['@vue/cli-service'].bare = true
  89. }
  90. // legacy support for router
  91. if (preset.router) {
  92. preset.plugins['@vue/cli-plugin-router'] = {}
  93. if (preset.routerHistoryMode) {
  94. preset.plugins['@vue/cli-plugin-router'].historyMode = true
  95. }
  96. }
  97. // legacy support for vuex
  98. if (preset.vuex) {
  99. preset.plugins['@vue/cli-plugin-vuex'] = {}
  100. }
  101. const packageManager = (
  102. cliOptions.packageManager ||
  103. loadOptions().packageManager ||
  104. (hasYarn() ? 'yarn' : null) ||
  105. (hasPnpm3OrLater() ? 'pnpm' : 'npm')
  106. )
  107. const pm = new PackageManager({ context, forcePackageManager: packageManager })
  108. await clearConsole()
  109. logWithSpinner(`✨`, `Creating project in ${chalk.yellow(context)}.`)
  110. this.emit('creation', { event: 'creating' })
  111. // get latest CLI plugin version
  112. const { latestMinor } = await getVersions()
  113. // generate package.json with plugin dependencies
  114. const pkg = {
  115. name,
  116. version: '0.1.0',
  117. private: true,
  118. devDependencies: {},
  119. ...resolvePkg(context)
  120. }
  121. const deps = Object.keys(preset.plugins)
  122. deps.forEach(dep => {
  123. if (preset.plugins[dep]._isPreset) {
  124. return
  125. }
  126. // Note: the default creator includes no more than `@vue/cli-*` & `@vue/babel-preset-env`,
  127. // so it is fine to only test `@vue` prefix.
  128. // Other `@vue/*` packages' version may not be in sync with the cli itself.
  129. pkg.devDependencies[dep] = (
  130. preset.plugins[dep].version ||
  131. ((/^@vue/.test(dep)) ? `~${latestMinor}` : `latest`)
  132. )
  133. })
  134. // write package.json
  135. await writeFileTree(context, {
  136. 'package.json': JSON.stringify(pkg, null, 2)
  137. })
  138. // intilaize git repository before installing deps
  139. // so that vue-cli-service can setup git hooks.
  140. const shouldInitGit = this.shouldInitGit(cliOptions)
  141. if (shouldInitGit) {
  142. logWithSpinner(`🗃`, `Initializing git repository...`)
  143. this.emit('creation', { event: 'git-init' })
  144. await run('git init')
  145. }
  146. // install plugins
  147. stopSpinner()
  148. log(`⚙\u{fe0f} Installing CLI plugins. This might take a while...`)
  149. log()
  150. this.emit('creation', { event: 'plugins-install' })
  151. if (isTestOrDebug && !process.env.VUE_CLI_TEST_DO_INSTALL_PLUGIN) {
  152. // in development, avoid installation process
  153. await require('./util/setupDevProject')(context)
  154. } else {
  155. await pm.install()
  156. }
  157. // run generator
  158. log(`🚀 Invoking generators...`)
  159. this.emit('creation', { event: 'invoking-generators' })
  160. const plugins = await this.resolvePlugins(preset.plugins)
  161. const generator = new Generator(context, {
  162. pkg,
  163. plugins,
  164. afterInvokeCbs,
  165. afterAnyInvokeCbs
  166. })
  167. await generator.generate({
  168. extractConfigFiles: preset.useConfigFiles
  169. })
  170. // install additional deps (injected by generators)
  171. log(`📦 Installing additional dependencies...`)
  172. this.emit('creation', { event: 'deps-install' })
  173. log()
  174. if (!isTestOrDebug) {
  175. await pm.install()
  176. }
  177. // run complete cbs if any (injected by generators)
  178. logWithSpinner('⚓', `Running completion hooks...`)
  179. this.emit('creation', { event: 'completion-hooks' })
  180. for (const cb of afterInvokeCbs) {
  181. await cb()
  182. }
  183. for (const cb of afterAnyInvokeCbs) {
  184. await cb()
  185. }
  186. // generate README.md
  187. stopSpinner()
  188. log()
  189. logWithSpinner('📄', 'Generating README.md...')
  190. await writeFileTree(context, {
  191. 'README.md': generateReadme(generator.pkg, packageManager)
  192. })
  193. // generate a .npmrc file for pnpm, to persist the `shamefully-flatten` flag
  194. if (packageManager === 'pnpm') {
  195. const pnpmConfig = hasPnpmVersionOrLater('4.0.0')
  196. ? 'shamefully-hoist=true\n'
  197. : 'shamefully-flatten=true\n'
  198. await writeFileTree(context, {
  199. '.npmrc': pnpmConfig
  200. })
  201. }
  202. // commit initial state
  203. let gitCommitFailed = false
  204. if (shouldInitGit) {
  205. await run('git add -A')
  206. if (isTestOrDebug) {
  207. await run('git', ['config', 'user.name', 'test'])
  208. await run('git', ['config', 'user.email', 'test@test.com'])
  209. }
  210. const msg = typeof cliOptions.git === 'string' ? cliOptions.git : 'init'
  211. try {
  212. await run('git', ['commit', '-m', msg])
  213. } catch (e) {
  214. gitCommitFailed = true
  215. }
  216. }
  217. // log instructions
  218. stopSpinner()
  219. log()
  220. log(`🎉 Successfully created project ${chalk.yellow(name)}.`)
  221. if (!cliOptions.skipGetStarted) {
  222. log(
  223. `👉 Get started with the following commands:\n\n` +
  224. (this.context === process.cwd() ? `` : chalk.cyan(` ${chalk.gray('$')} cd ${name}\n`)) +
  225. chalk.cyan(` ${chalk.gray('$')} ${packageManager === 'yarn' ? 'yarn serve' : packageManager === 'pnpm' ? 'pnpm run serve' : 'npm run serve'}`)
  226. )
  227. }
  228. log()
  229. this.emit('creation', { event: 'done' })
  230. if (gitCommitFailed) {
  231. warn(
  232. `Skipped git commit due to missing username and email in git config.\n` +
  233. `You will need to perform the initial commit yourself.\n`
  234. )
  235. }
  236. generator.printExitLogs()
  237. }
  238. run (command, args) {
  239. if (!args) { [command, ...args] = command.split(/\s+/) }
  240. return execa(command, args, { cwd: this.context })
  241. }
  242. async promptAndResolvePreset (answers = null) {
  243. // prompt
  244. if (!answers) {
  245. await clearConsole(true)
  246. answers = await inquirer.prompt(this.resolveFinalPrompts())
  247. }
  248. debug('vue-cli:answers')(answers)
  249. if (answers.packageManager) {
  250. saveOptions({
  251. packageManager: answers.packageManager
  252. })
  253. }
  254. let preset
  255. if (answers.preset && answers.preset !== '__manual__') {
  256. preset = await this.resolvePreset(answers.preset)
  257. } else {
  258. // manual
  259. preset = {
  260. useConfigFiles: answers.useConfigFiles === 'files',
  261. plugins: {}
  262. }
  263. answers.features = answers.features || []
  264. // run cb registered by prompt modules to finalize the preset
  265. this.promptCompleteCbs.forEach(cb => cb(answers, preset))
  266. }
  267. // validate
  268. validatePreset(preset)
  269. // save preset
  270. if (answers.save && answers.saveName) {
  271. savePreset(answers.saveName, preset)
  272. }
  273. debug('vue-cli:preset')(preset)
  274. return preset
  275. }
  276. async resolvePreset (name, clone) {
  277. let preset
  278. const savedPresets = loadOptions().presets || {}
  279. if (name in savedPresets) {
  280. preset = savedPresets[name]
  281. } else if (name.endsWith('.json') || /^\./.test(name) || path.isAbsolute(name)) {
  282. preset = await loadLocalPreset(path.resolve(name))
  283. } else if (name.includes('/')) {
  284. logWithSpinner(`Fetching remote preset ${chalk.cyan(name)}...`)
  285. this.emit('creation', { event: 'fetch-remote-preset' })
  286. try {
  287. preset = await loadRemotePreset(name, clone)
  288. stopSpinner()
  289. } catch (e) {
  290. stopSpinner()
  291. error(`Failed fetching remote preset ${chalk.cyan(name)}:`)
  292. throw e
  293. }
  294. }
  295. // use default preset if user has not overwritten it
  296. if (name === 'default' && !preset) {
  297. preset = defaults.presets.default
  298. }
  299. if (!preset) {
  300. error(`preset "${name}" not found.`)
  301. const presets = Object.keys(savedPresets)
  302. if (presets.length) {
  303. log()
  304. log(`available presets:\n${presets.join(`\n`)}`)
  305. } else {
  306. log(`you don't seem to have any saved preset.`)
  307. log(`run vue-cli in manual mode to create a preset.`)
  308. }
  309. exit(1)
  310. }
  311. return preset
  312. }
  313. // { id: options } => [{ id, apply, options }]
  314. async resolvePlugins (rawPlugins) {
  315. // ensure cli-service is invoked first
  316. rawPlugins = sortObject(rawPlugins, ['@vue/cli-service'], true)
  317. const plugins = []
  318. for (const id of Object.keys(rawPlugins)) {
  319. const apply = loadModule(`${id}/generator`, this.context) || (() => {})
  320. let options = rawPlugins[id] || {}
  321. if (options.prompts) {
  322. const prompts = loadModule(`${id}/prompts`, this.context)
  323. if (prompts) {
  324. log()
  325. log(`${chalk.cyan(options._isPreset ? `Preset options:` : id)}`)
  326. options = await inquirer.prompt(prompts)
  327. }
  328. }
  329. plugins.push({ id, apply, options })
  330. }
  331. return plugins
  332. }
  333. getPresets () {
  334. const savedOptions = loadOptions()
  335. return Object.assign({}, savedOptions.presets, defaults.presets)
  336. }
  337. resolveIntroPrompts () {
  338. const presets = this.getPresets()
  339. const presetChoices = Object.keys(presets).map(name => {
  340. return {
  341. name: `${name} (${formatFeatures(presets[name])})`,
  342. value: name
  343. }
  344. })
  345. const presetPrompt = {
  346. name: 'preset',
  347. type: 'list',
  348. message: `Please pick a preset:`,
  349. choices: [
  350. ...presetChoices,
  351. {
  352. name: 'Manually select features',
  353. value: '__manual__'
  354. }
  355. ]
  356. }
  357. const featurePrompt = {
  358. name: 'features',
  359. when: isManualMode,
  360. type: 'checkbox',
  361. message: 'Check the features needed for your project:',
  362. choices: [],
  363. pageSize: 10
  364. }
  365. return {
  366. presetPrompt,
  367. featurePrompt
  368. }
  369. }
  370. resolveOutroPrompts () {
  371. const outroPrompts = [
  372. {
  373. name: 'useConfigFiles',
  374. when: isManualMode,
  375. type: 'list',
  376. message: 'Where do you prefer placing config for Babel, ESLint, etc.?',
  377. choices: [
  378. {
  379. name: 'In dedicated config files',
  380. value: 'files'
  381. },
  382. {
  383. name: 'In package.json',
  384. value: 'pkg'
  385. }
  386. ]
  387. },
  388. {
  389. name: 'save',
  390. when: isManualMode,
  391. type: 'confirm',
  392. message: 'Save this as a preset for future projects?',
  393. default: false
  394. },
  395. {
  396. name: 'saveName',
  397. when: answers => answers.save,
  398. type: 'input',
  399. message: 'Save preset as:'
  400. }
  401. ]
  402. // ask for packageManager once
  403. const savedOptions = loadOptions()
  404. if (!savedOptions.packageManager && (hasYarn() || hasPnpm3OrLater())) {
  405. const packageManagerChoices = []
  406. if (hasYarn()) {
  407. packageManagerChoices.push({
  408. name: 'Use Yarn',
  409. value: 'yarn',
  410. short: 'Yarn'
  411. })
  412. }
  413. if (hasPnpm3OrLater()) {
  414. packageManagerChoices.push({
  415. name: 'Use PNPM',
  416. value: 'pnpm',
  417. short: 'PNPM'
  418. })
  419. }
  420. packageManagerChoices.push({
  421. name: 'Use NPM',
  422. value: 'npm',
  423. short: 'NPM'
  424. })
  425. outroPrompts.push({
  426. name: 'packageManager',
  427. type: 'list',
  428. message: 'Pick the package manager to use when installing dependencies:',
  429. choices: packageManagerChoices
  430. })
  431. }
  432. return outroPrompts
  433. }
  434. resolveFinalPrompts () {
  435. // patch generator-injected prompts to only show in manual mode
  436. this.injectedPrompts.forEach(prompt => {
  437. const originalWhen = prompt.when || (() => true)
  438. prompt.when = answers => {
  439. return isManualMode(answers) && originalWhen(answers)
  440. }
  441. })
  442. const prompts = [
  443. this.presetPrompt,
  444. this.featurePrompt,
  445. ...this.injectedPrompts,
  446. ...this.outroPrompts
  447. ]
  448. debug('vue-cli:prompts')(prompts)
  449. return prompts
  450. }
  451. shouldInitGit (cliOptions) {
  452. if (!hasGit()) {
  453. return false
  454. }
  455. // --git
  456. if (cliOptions.forceGit) {
  457. return true
  458. }
  459. // --no-git
  460. if (cliOptions.git === false || cliOptions.git === 'false') {
  461. return false
  462. }
  463. // default: true unless already in a git repo
  464. return !hasProjectGit(this.context)
  465. }
  466. }