index.ts 2.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7
import type { ConfigEnv, UserConfig } from 'vite'
import debug from 'debug'
import {
  M,
  defineUniMainJsPlugin,
  getUniStatistics,
  parseManifestJsonOnce,
fxy060608's avatar
fxy060608 已提交
8
  parsePagesJson,
fxy060608's avatar
fxy060608 已提交
9 10 11 12 13 14
} from '@dcloudio/uni-cli-shared'

export default [
  defineUniMainJsPlugin((opts) => {
    let isEnable = false
    return {
fxy060608's avatar
fxy060608 已提交
15
      name: 'uni:stat',
fxy060608's avatar
fxy060608 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
      enforce: 'pre',
      config(config, env) {
        if (isSsr(env.command, config)) {
          return
        }
        const inputDir = process.env.UNI_INPUT_DIR!
        const platform = process.env.UNI_PLATFORM!
        isEnable = getUniStatistics(inputDir, platform).enable === true
        if (process.env.NODE_ENV === 'production') {
          const manifestJson = parseManifestJsonOnce(inputDir)
          if (!manifestJson.appid) {
            console.log()
            console.warn(M['stat.warn.appid'])
            console.log()
            isEnable = false
          }
        }
        const titlesJson = Object.create(null)
        if (isEnable) {
fxy060608's avatar
fxy060608 已提交
35 36 37 38 39 40 41 42
          parsePagesJson(inputDir, platform).pages.forEach((page: any) => {
            const style = page.style || {}
            const titleText =
              // MP
              style.navigationBarTitleText ||
              // H5 || App
              style.navigationBar?.titleText ||
              ''
fxy060608's avatar
fxy060608 已提交
43 44 45 46 47
            if (titleText) {
              titlesJson[page.path] = titleText
            }
          })
        }
fxy060608's avatar
fxy060608 已提交
48
        debug('uni:stat')('isEnable', isEnable)
fxy060608's avatar
fxy060608 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        process.env.UNI_STAT_TITLE_JSON = JSON.stringify(titlesJson)
        return {
          define: {
            'process.env.UNI_STAT_TITLE_JSON': process.env.UNI_STAT_TITLE_JSON,
          },
        }
      },
      transform(code, id) {
        if (isEnable && opts.filter(id)) {
          return {
            code: code + `;import '@dcloudio/uni-stat';`,
            map: null,
          }
        }
      },
    }
  }),
]

function isSsr(command: ConfigEnv['command'], config: UserConfig) {
  if (command === 'serve') {
    return !!(config.server && config.server.middlewareMode)
  }
  if (command === 'build') {
    return !!(config.build && config.build.ssr)
  }
  return false
}