action.ts 1.6 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import { extend } from '@vue/shared'
fxy060608's avatar
fxy060608 已提交
2
import { RollupWatcher } from 'rollup'
fxy060608's avatar
fxy060608 已提交
3
import { BuildOptions, ServerOptions } from 'vite'
fxy060608's avatar
fxy060608 已提交
4
import { M } from '@dcloudio/uni-cli-shared'
fxy060608's avatar
fxy060608 已提交
5 6 7 8 9 10
import { CliOptions } from '.'
import { build, buildSSR } from './build'
import { createServer, createSSRServer } from './server'
import { initEnv } from './utils'

export async function runDev(options: CliOptions & ServerOptions) {
fxy060608's avatar
fxy060608 已提交
11
  extend(options, { watch: true, minify: false })
fxy060608's avatar
fxy060608 已提交
12 13 14 15 16
  initEnv('dev', options)
  try {
    if (options.platform === 'h5') {
      await (options.ssr ? createSSRServer(options) : createServer(options))
    } else {
fxy060608's avatar
fxy060608 已提交
17
      const watcher = (await build(options)) as RollupWatcher
fxy060608's avatar
fxy060608 已提交
18
      let isFirst = true
fxy060608's avatar
fxy060608 已提交
19
      watcher.on('event', (event) => {
fxy060608's avatar
fxy060608 已提交
20
        if (event.code === 'BUNDLE_START') {
fxy060608's avatar
fxy060608 已提交
21 22 23
          if (isFirst) {
            return (isFirst = false)
          }
fxy060608's avatar
fxy060608 已提交
24 25
          console.log(M['dev.watching.start'])
        } else if (event.code === 'BUNDLE_END') {
fxy060608's avatar
fxy060608 已提交
26
          event.result.close()
fxy060608's avatar
fxy060608 已提交
27
          console.log(M['dev.watching.end'])
fxy060608's avatar
fxy060608 已提交
28 29
        }
      })
fxy060608's avatar
fxy060608 已提交
30 31
    }
  } catch (e) {
32 33 34 35 36
    if (options.platform === 'h5') {
      console.error(`error when starting dev server:\n${e.stack || e}`)
    } else {
      console.error(`error during build:\n${e.stack || e}`)
    }
fxy060608's avatar
fxy060608 已提交
37 38 39 40 41 42 43 44 45 46
    process.exit(1)
  }
}

export async function runBuild(options: CliOptions & BuildOptions) {
  initEnv('build', options)
  try {
    await (options.ssr && options.platform === 'h5'
      ? buildSSR(options)
      : build(options))
fxy060608's avatar
fxy060608 已提交
47
    console.log(M['build.done'])
fxy060608's avatar
fxy060608 已提交
48
  } catch (e) {
fxy060608's avatar
fxy060608 已提交
49
    console.error(`error during build:\n${e.stack || e}`)
fxy060608's avatar
fxy060608 已提交
50 51 52
    process.exit(1)
  }
}