plugin-init.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // 手动添加完插件后执行此脚本进行初始化动作
  2. const fs = require('fs-extra')
  3. // eslint-disable-next-line import/no-extraneous-dependencies
  4. const path = require('path')
  5. const chalk = require('chalk')
  6. const shell = require('shelljs')
  7. const inquirer = require('inquirer')
  8. const getAllPlugin = require('./lib/plugin-get-all')
  9. const semverValidate = require('./lib/semver-validate')
  10. const installDep = require('./lib/install-dep')
  11. const projectPackage = require('../package.json')
  12. const pluginsPath = path.resolve(__dirname, '../src/plugin')
  13. // 检测是否有插件文件夹
  14. if (!fs.existsSync(pluginsPath)) {
  15. console.log(chalk.red('未找到插件文件夹目录, 请确认 src 文件夹中是否有 plugins 目录'))
  16. process.exit(1)
  17. }
  18. const pluginList = getAllPlugin(pluginsPath)
  19. // 将数组 forEach 异步化
  20. async function asyncForEach(array, callback) {
  21. for (let index = 0; index < array.length; index++) {
  22. // eslint-disable-next-line
  23. await callback(array[index], index, array)
  24. }
  25. }
  26. // 监测 npm 是否已安装
  27. if (!shell.which('npm')) {
  28. console.log(chalk.red('检测到未安装 npm, 请先安装 npm 再重新执行, 查看: https://www.npmjs.com/get-npm'))
  29. process.exit(1)
  30. }
  31. async function handler() {
  32. const questions = [
  33. {
  34. type: 'checkbox',
  35. name: 'plugin',
  36. choices: pluginList.map(item => ({ name: item.name, value: item })),
  37. message: '请选择需要初始化的插件\n',
  38. },
  39. ]
  40. const { plugins } = await inquirer.prompt(questions)
  41. if (plugins.length === 0) {
  42. console.log('未选择需要初始化的插件')
  43. return
  44. }
  45. console.log(chalk.green(`开始初始化插件 ${plugins.map(item => item.name).join(', ')}`))
  46. await asyncForEach(plugins, async ({ name, packageCtx }) => {
  47. console.log(`* 插件 ${name}`)
  48. const keys = ['dependencies', 'devDependencies']
  49. let hasError = false
  50. await asyncForEach(keys, async key => {
  51. await asyncForEach(Object.keys(packageCtx[key]), async pkg => {
  52. const v1 = packageCtx[key][pkg]
  53. const v2 = projectPackage[key][pkg]
  54. if (v1 && v2) {
  55. if (!semverValidate(v1, v2)) {
  56. return
  57. }
  58. }
  59. try {
  60. await installDep(pkg, v1, projectPackage, key === 'devDependencies')
  61. } catch (e) {
  62. hasError = true
  63. console.log(chalk.red(e.message))
  64. }
  65. // const result = await installDep(pkg, v1, projectPackage, (key === 'devDependencies'))
  66. // if (result instanceof Error) {
  67. // hasError = true
  68. // console.log(chalk.red(result.message))
  69. // }
  70. })
  71. })
  72. if (hasError) {
  73. console.log(chalk.yellow('插件初始化结束, 但存在问题, 请手动解决'))
  74. }
  75. })
  76. }
  77. handler().then(() => {
  78. // eslint-disable-next-line
  79. require('./plugin-get-config')
  80. })