cnf
2025-05-10 386fa0eca75ddc88165f9b73038f2a2239e1072e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const debug = require('debug')
const {
  M,
  defineUniMainJsPlugin,
  getUniStatistics,
  parseManifestJsonOnce,
  parsePagesJsonOnce,
} = require('@dcloudio/uni-cli-shared')
 
module.exports = [
  defineUniMainJsPlugin((opts) => {
    let isEnable = false
    return {
      name: 'vite:uni-stat',
      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) {
          parsePagesJsonOnce(inputDir, platform).pages.forEach((page) => {
            const titleText = page.style.navigationBar.titleText || ''
            if (titleText) {
              titlesJson[page.path] = titleText
            }
          })
        }
        debug('vite:uni:stat')('isEnable', isEnable)
        return {
          define: {
            'process.env.UNI_STAT_TITLE_JSON': JSON.stringify(titlesJson),
          },
        }
      },
      transform(code, id) {
        if (isEnable && opts.filter(id)) {
          return {
            code: code + `;import '@dcloudio/uni-stat';`,
            map: null,
          }
        }
      },
    }
  }),
]
 
function isSsr(command, config) {
  if (command === 'serve') {
    return !!(config.server && config.server.middlewareMode)
  }
  if (command === 'build') {
    return !!(config.build && config.build.ssr)
  }
  return false
}