utils.ts 8.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import fs from 'fs'
fxy060608's avatar
fxy060608 已提交
2
import os from 'os'
fxy060608's avatar
fxy060608 已提交
3
import path from 'path'
fxy060608's avatar
fxy060608 已提交
4
import colors from 'picocolors'
fxy060608's avatar
fxy060608 已提交
5
import { performance } from 'perf_hooks'
fxy060608's avatar
fxy060608 已提交
6
import type { BuildOptions, InlineConfig, Logger } from 'vite'
fxy060608's avatar
fxy060608 已提交
7

fxy060608's avatar
fxy060608 已提交
8 9 10 11 12
import {
  M,
  isInHBuilderX,
  initModulePaths,
  parseScripts,
fxy060608's avatar
fxy060608 已提交
13
  getPlatformDir,
14
  output,
fxy060608's avatar
fxy060608 已提交
15
} from '@dcloudio/uni-cli-shared'
fxy060608's avatar
fxy060608 已提交
16

fxy060608's avatar
fxy060608 已提交
17
import { CliOptions } from '.'
fxy060608's avatar
fxy060608 已提交
18
import { initNVueEnv } from './nvue'
fxy060608's avatar
fxy060608 已提交
19 20 21 22 23 24 25

export const PLATFORMS = [
  'app',
  'h5',
  'mp-alipay',
  'mp-baidu',
  'mp-qq',
fxy060608's avatar
fxy060608 已提交
26
  'mp-lark',
fxy060608's avatar
fxy060608 已提交
27 28
  'mp-toutiao',
  'mp-weixin',
fxy060608's avatar
fxy060608 已提交
29
  'quickapp-webview',
fxy060608's avatar
fxy060608 已提交
30 31 32 33
  'quickapp-webview-huawei',
  'quickapp-webview-union',
]

34 35 36 37 38 39 40 41 42 43 44 45 46
export type PLATFORM =
  | 'app'
  | 'mp-alipay'
  | 'mp-baidu'
  | 'mp-kuaishou'
  | 'mp-lark'
  | 'mp-qq'
  | 'mp-toutiao'
  | 'mp-weixin'
  | 'quickapp-webview'
  | 'quickapp-webview-huawei'
  | 'quickapp-webview-union'

fxy060608's avatar
fxy060608 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
function resolveConfigFile() {
  const viteConfigJs = path.resolve(process.env.UNI_INPUT_DIR, 'vite.config.js')
  const viteConfigTs = path.resolve(process.env.UNI_INPUT_DIR, 'vite.config.ts')

  if (fs.existsSync(viteConfigTs)) {
    return viteConfigTs
  }
  if (fs.existsSync(viteConfigJs)) {
    return viteConfigJs
  }
  return path.resolve(process.env.UNI_CLI_CONTEXT, 'vite.config.js')
}

export function addConfigFile(inlineConfig: InlineConfig) {
  if (isInHBuilderX()) {
    inlineConfig.configFile = resolveConfigFile()
  }
  return inlineConfig
}

fxy060608's avatar
fxy060608 已提交
67
let initialized = false
fxy060608's avatar
fxy060608 已提交
68 69 70 71
export function initEnv(
  type: 'unknown' | 'dev' | 'build',
  options: CliOptions
) {
fxy060608's avatar
fxy060608 已提交
72
  if (initialized) {
fxy060608's avatar
fxy060608 已提交
73 74
    return
  }
fxy060608's avatar
fxy060608 已提交
75
  initialized = true
fxy060608's avatar
fxy060608 已提交
76 77 78 79
  if (options.platform === 'mp-360') {
    console.error(M['mp.360.unsupported'])
    process.exit(0)
  }
fxy060608's avatar
fxy060608 已提交
80 81 82
  if (options.plugin) {
    process.env.UNI_MP_PLUGIN = 'true'
  }
fxy060608's avatar
fxy060608 已提交
83
  // TODO 需要识别 mode
fxy060608's avatar
fxy060608 已提交
84 85 86 87 88 89 90 91 92
  if (type === 'dev') {
    process.env.NODE_ENV = 'development'
  } else if (type === 'build') {
    if ((options as BuildOptions).watch) {
      process.env.NODE_ENV = 'development'
    } else {
      process.env.NODE_ENV = 'production'
    }
  }
fxy060608's avatar
fxy060608 已提交
93 94 95
  if (!options.mode) {
    options.mode = process.env.NODE_ENV
  }
96 97 98
  // vite 会修改 NODE_ENV,存储在 UNI_NODE_ENV 中,稍后校正 NODE_ENV
  process.env.UNI_NODE_ENV = process.env.VITE_USER_NODE_ENV =
    process.env.NODE_ENV
fxy060608's avatar
fxy060608 已提交
99

fxy060608's avatar
fxy060608 已提交
100 101 102
  process.env.UNI_CLI_CONTEXT = isInHBuilderX()
    ? path.resolve(process.env.UNI_HBUILDERX_PLUGINS!, 'uniapp-cli-vite')
    : process.cwd()
fxy060608's avatar
fxy060608 已提交
103

fxy060608's avatar
fxy060608 已提交
104
  // TODO 待优化
fxy060608's avatar
fxy060608 已提交
105
  initUTSPlatform(options)
fxy060608's avatar
fxy060608 已提交
106

fxy060608's avatar
fxy060608 已提交
107 108 109 110 111 112 113
  if (
    options.platform === 'quickapp-webview-huawei' ||
    options.platform === 'quickapp-webview-union'
  ) {
    process.env.UNI_SUB_PLATFORM = options.platform
    options.platform = 'quickapp-webview'
  }
fxy060608's avatar
fxy060608 已提交
114 115
  process.env.VITE_ROOT_DIR =
    process.env.VITE_ROOT_DIR || process.env.UNI_INPUT_DIR || process.cwd()
fxy060608's avatar
fxy060608 已提交
116

fxy060608's avatar
fxy060608 已提交
117 118 119
  process.env.UNI_INPUT_DIR =
    process.env.UNI_INPUT_DIR || path.resolve(process.cwd(), 'src')

fxy060608's avatar
fxy060608 已提交
120 121 122 123
  initCustomScripts(options)

  process.env.UNI_PLATFORM = options.platform as UniApp.PLATFORM

fxy060608's avatar
fxy060608 已提交
124 125
  const hasOutputDir = !!process.env.UNI_OUTPUT_DIR
  if (hasOutputDir) {
fxy060608's avatar
fxy060608 已提交
126 127 128
    ;(options as BuildOptions).outDir = process.env.UNI_OUTPUT_DIR
  } else {
    if (!(options as BuildOptions).outDir) {
fxy060608's avatar
fxy060608 已提交
129 130
      ;(options as BuildOptions).outDir = path.resolve(
        process.cwd(),
fxy060608's avatar
fxy060608 已提交
131 132
        'dist',
        process.env.NODE_ENV === 'production' ? 'build' : 'dev',
fxy060608's avatar
fxy060608 已提交
133
        getPlatformDir()
fxy060608's avatar
fxy060608 已提交
134 135 136 137
      )
    }
    process.env.UNI_OUTPUT_DIR = (options as BuildOptions).outDir!
  }
fxy060608's avatar
fxy060608 已提交
138 139 140 141
  // 兼容 HBuilderX 旧参数
  if (process.env.UNI_SUBPACKGE) {
    options.subpackage = process.env.UNI_SUBPACKGE
  }
fxy060608's avatar
fxy060608 已提交
142 143
  if (options.subpackage) {
    process.env.UNI_SUBPACKAGE = options.subpackage
fxy060608's avatar
fxy060608 已提交
144 145 146 147 148
    if (!hasOutputDir) {
      // 未指定,则自动补充
      process.env.UNI_OUTPUT_DIR = (options as BuildOptions).outDir =
        path.resolve(process.env.UNI_OUTPUT_DIR, options.subpackage)
    }
fxy060608's avatar
fxy060608 已提交
149 150
  }

fxy060608's avatar
fxy060608 已提交
151 152
  initAutomator(options)

fxy060608's avatar
fxy060608 已提交
153 154
  initDevtools(options)

fxy060608's avatar
fxy060608 已提交
155
  if (process.env.UNI_PLATFORM === 'app') {
fxy060608's avatar
fxy060608 已提交
156 157 158 159 160 161 162
    const pkg = require('../../package.json')
    console.log(
      M['app.compiler.version'].replace(
        '{version}',
        pkg['uni-app']['compilerVersion'] + '(vue3)'
      )
    )
fxy060608's avatar
fxy060608 已提交
163 164
    initNVueEnv()
  }
fxy060608's avatar
fxy060608 已提交
165 166 167 168 169 170 171 172 173

  if (process.env.NODE_ENV === 'development') {
    console.log(
      M['dev.performance'] +
        (process.env.UNI_PLATFORM.startsWith('mp-')
          ? M['dev.performance.mp']
          : '')
    )
  }
fxy060608's avatar
fxy060608 已提交
174

D
DCloud_LXH 已提交
175 176 177 178 179 180 181
  if (
    (options as BuildOptions).sourcemap &&
    process.env.NODE_ENV === 'production'
  ) {
    process.env.SOURCEMAP = 'true'
  }

fxy060608's avatar
fxy060608 已提交
182 183
  initModulePaths()

fxy060608's avatar
fxy060608 已提交
184
  console.log(M['compiling'])
fxy060608's avatar
fxy060608 已提交
185
}
fxy060608's avatar
fxy060608 已提交
186

fxy060608's avatar
fxy060608 已提交
187
function initUTSPlatform(options: CliOptions) {
fxy060608's avatar
fxy060608 已提交
188 189 190 191 192 193 194
  if (options.platform === 'app-android') {
    process.env.UNI_UTS_PLATFORM = 'app-android'
    options.platform = 'app'
  } else if (options.platform === 'app-ios') {
    process.env.UNI_UTS_PLATFORM = 'app-ios'
    options.platform = 'app'
  } else {
fxy060608's avatar
fxy060608 已提交
195
    // 运行时,可能传入了 UNI_APP_PLATFORM = 'android'|'ios'
fxy060608's avatar
fxy060608 已提交
196 197 198 199 200 201 202 203 204 205
    if (process.env.UNI_APP_PLATFORM === 'android') {
      process.env.UNI_UTS_PLATFORM = 'app-android'
    }
    if (process.env.UNI_APP_PLATFORM === 'ios') {
      process.env.UNI_UTS_PLATFORM = 'app-ios'
    }
    if (options.platform === 'app-plus') {
      options.platform = 'app'
    }
  }
fxy060608's avatar
fxy060608 已提交
206 207 208
  if (options.platform === 'h5') {
    process.env.UNI_UTS_PLATFORM = 'web'
  }
fxy060608's avatar
fxy060608 已提交
209 210 211 212 213 214
  // 非 app 平台,自动补充 UNI_UTS_PLATFORM
  // app 平台,必须主动传入
  if (options.platform !== 'app') {
    if (!process.env.UNI_UTS_PLATFORM) {
      process.env.UNI_UTS_PLATFORM = options.platform as any
    }
fxy060608's avatar
fxy060608 已提交
215
  }
fxy060608's avatar
fxy060608 已提交
216 217
}

fxy060608's avatar
fxy060608 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230
function initDevtools({ devtools, devtoolsHost, devtoolsPort }: CliOptions) {
  if (!devtools) {
    return
  }
  process.env.__VUE_PROD_DEVTOOLS__ = 'true'
  if (devtoolsHost) {
    process.env.__VUE_DEVTOOLS_HOST__ = devtoolsHost
  }
  if (devtoolsPort) {
    process.env.__VUE_DEVTOOLS_PORT__ = devtoolsPort + ''
  }
}

fxy060608's avatar
fxy060608 已提交
231
function initAutomator({ autoHost, autoPort }: CliOptions) {
fxy060608's avatar
fxy060608 已提交
232 233
  // 发行分包,插件也不需要自动化测试
  if (!autoPort || process.env.UNI_SUBPACKAGE || process.env.UNI_MP_PLUGIN) {
fxy060608's avatar
fxy060608 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    return
  }
  process.env.UNI_AUTOMATOR_WS_ENDPOINT =
    'ws://' + (autoHost || resolveHostname()) + ':' + autoPort
}

function resolveHostname() {
  const interfaces = os.networkInterfaces()
  const keys = Object.keys(interfaces)
  for (const key of keys) {
    const interfaceInfos = interfaces[key]
    if (!interfaceInfos) {
      continue
    }
    for (const info of interfaceInfos) {
249 250 251 252 253
      if (
        (info.family === 'IPv4' ||
          /* Node >= v18 */ (info as any).family === 4) &&
        !info.address.includes('127.0.0.1')
      ) {
fxy060608's avatar
fxy060608 已提交
254 255 256 257 258 259 260
        return info.address
      }
    }
  }
  return 'localhost'
}

fxy060608's avatar
fxy060608 已提交
261 262 263 264
export function cleanOptions(options: CliOptions) {
  const ret = { ...options }
  delete ret['--']

fxy060608's avatar
fxy060608 已提交
265 266 267
  delete ret.c
  delete ret.config

fxy060608's avatar
fxy060608 已提交
268 269 270 271
  delete ret.platform
  delete ret.p
  delete ret.ssr

272
  delete ret.base
fxy060608's avatar
fxy060608 已提交
273 274 275 276 277 278 279
  delete ret.debug
  delete ret.d
  delete ret.filter
  delete ret.f
  delete ret.logLevel
  delete ret.l
  delete ret.clearScreen
280 281
  delete ret.m
  delete ret.mode
fxy060608's avatar
fxy060608 已提交
282 283 284 285

  delete ret.autoHost
  delete ret.autoPort

fxy060608's avatar
fxy060608 已提交
286 287
  return ret
}
fxy060608's avatar
fxy060608 已提交
288

fxy060608's avatar
fxy060608 已提交
289 290 291 292
export function printStartupDuration(
  logger: Logger,
  whitespace: boolean = true
) {
fxy060608's avatar
fxy060608 已提交
293 294 295 296 297
  // @ts-ignore
  if (global.__vite_start_time) {
    // @ts-ignore
    const startupDuration = performance.now() - global.__vite_start_time
    logger.info(
fxy060608's avatar
fxy060608 已提交
298
      `${whitespace ? `\n  ` : ''}${colors.cyan(
fxy060608's avatar
fxy060608 已提交
299 300
        `ready in ${Math.ceil(startupDuration)}ms.`
      )}\n`
fxy060608's avatar
fxy060608 已提交
301 302 303
    )
  }
}
fxy060608's avatar
fxy060608 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317

function initCustomScripts(options: CliOptions) {
  const custom = parseScripts(
    process.env.UNI_SCRIPT || options.platform!, // process.env.UNI_SCRIPT 是 HBuilderX 传递的
    path.join(process.env.VITE_ROOT_DIR!, 'package.json')
  )
  if (!custom) {
    return
  }
  options.platform = custom.platform
  process.env.UNI_CUSTOM_SCRIPT = custom.name
  process.env.UNI_CUSTOM_DEFINE = JSON.stringify(custom.define)
  process.env.UNI_CUSTOM_CONTEXT = JSON.stringify(custom.context)
}
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

export function showRunPrompt(platform: PLATFORM) {
  if (!isInHBuilderX()) {
    const devtools = getPlatformDevtools(getOriginalPlatform(platform))
    const outputDir = path.relative(
      process.env.UNI_CLI_CONTEXT,
      process.env.UNI_OUTPUT_DIR
    )
    output(
      'log',
      `${M['prompt.run.message']
        .replace('{devtools}', M[devtools])
        .replace('{outputDir}', colors.cyan(outputDir))}`
    )
  }
}

function getOriginalPlatform(platform: PLATFORM) {
  if (platform.startsWith('quickapp-webview') && process.env.UNI_SUB_PLATFORM) {
    return process.env.UNI_SUB_PLATFORM
  }
  return platform
}

function getPlatformDevtools(platform: PLATFORM) {
  return `prompt.run.devtools.${platform}` as keyof typeof M
}