invoke.js 1.2 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6
const fs = require('fs')
const path = require('path')

module.exports = async function add (argv) {
  const pluginName = argv._[1]
  if (!pluginName) {
fxy060608's avatar
fxy060608 已提交
7
    console.error('请指定插件名称')
fxy060608's avatar
fxy060608 已提交
8 9 10 11 12
    process.exit(0)
  }
  const pluginPkg = require(pluginName + '/package.json')
  const options = pluginPkg['uni-app']
  if (!options) {
fxy060608's avatar
fxy060608 已提交
13
    console.error('插件不合法')
fxy060608's avatar
fxy060608 已提交
14 15 16 17
    process.exit(0)
  }
  const name = options.name
  if (!name) {
fxy060608's avatar
fxy060608 已提交
18
    console.error('插件名称不存在')
fxy060608's avatar
fxy060608 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    process.exit(0)
  }
  const scripts = options.scripts || {
    ['dev:' + name]: `cross-env NODE_ENV=development UNI_PLATFORM=${name} vue-cli-service uni-build --watch`,
    ['build:' + name]: `cross-env NODE_ENV=production UNI_PLATFORM=${name} vue-cli-service uni-build`
  }

  const pkgPath = path.resolve(process.cwd(), 'package.json')
  const pkg = require(pkgPath)
  if (!pkg.scripts) {
    pkg.scripts = {}
  }
  let changed = false
  Object.keys(scripts).forEach(script => {
    if (!pkg.scripts[script]) {
      changed = true
      pkg.scripts[script] = scripts[script]
    }
  })
  if (changed) {
    fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2))
  }
}