utils.ts 4.0 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import fs from 'fs'
fxy060608's avatar
fxy060608 已提交
2 3
import os from 'os'
import path from 'path'
fxy060608's avatar
fxy060608 已提交
4
import { camelize, capitalize } from '@vue/shared'
fxy060608's avatar
fxy060608 已提交
5
import { once } from '@dcloudio/uni-shared'
fxy060608's avatar
fxy060608 已提交
6
export { default as hash } from 'hash-sum'
fxy060608's avatar
fxy060608 已提交
7 8
import type { SFCTemplateCompileOptions } from '@vue/compiler-sfc'
import debug from 'debug'
fxy060608's avatar
fxy060608 已提交
9
import { PAGE_EXTNAME, PAGE_EXTNAME_APP } from './constants'
fxy060608's avatar
fxy060608 已提交
10

11 12 13 14 15 16
import {
  NodeTypes,
  ElementNode,
  RootNode,
  TemplateChildNode,
} from '@vue/compiler-core'
17
export const isWindows = os.platform() === 'win32'
fxy060608's avatar
fxy060608 已提交
18
export function normalizePath(id: string): string {
19
  return isWindows ? id.replace(/\\/g, '/') : id
fxy060608's avatar
fxy060608 已提交
20
}
fxy060608's avatar
fxy060608 已提交
21

雪洛's avatar
雪洛 已提交
22
export function checkElementNodeTag(
23
  node: RootNode | TemplateChildNode | null | undefined,
雪洛's avatar
雪洛 已提交
24 25
  tag: string
): node is ElementNode {
26
  return !!node && node.type === NodeTypes.ELEMENT && node.tag === tag
雪洛's avatar
雪洛 已提交
27 28
}

fxy060608's avatar
fxy060608 已提交
29 30 31
export const resolveMainPathOnce = once((inputDir: string) => {
  const mainTsPath = path.resolve(inputDir, 'main.ts')
  if (fs.existsSync(mainTsPath)) {
fxy060608's avatar
fxy060608 已提交
32
    return normalizePath(mainTsPath)
fxy060608's avatar
fxy060608 已提交
33
  }
fxy060608's avatar
fxy060608 已提交
34
  return normalizePath(path.resolve(inputDir, 'main.js'))
fxy060608's avatar
fxy060608 已提交
35
})
fxy060608's avatar
fxy060608 已提交
36

fxy060608's avatar
fxy060608 已提交
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 69 70 71 72 73 74 75 76 77 78
let componentsLibPath: string = ''
export function resolveComponentsLibPath() {
  if (!componentsLibPath) {
    componentsLibPath = path.resolve(
      resolveBuiltIn('@dcloudio/uni-components/package.json'),
      '../lib'
    )
  }
  return componentsLibPath
}

const ownerModules = ['@dcloudio/uni-app', '@dcloudio/vite-plugin-uni']

const paths: string[] = []

function initPaths() {
  const cliContext = process.env.UNI_CLI_CONTEXT
  if (cliContext) {
    const pathSet = new Set<string>()
    pathSet.add(path.join(cliContext, 'node_modules'))
    ;[`@dcloudio/uni-` + process.env.UNI_PLATFORM, ...ownerModules].forEach(
      (ownerModule) => {
        try {
          pathSet.add(
            path.resolve(
              require.resolve(ownerModule + '/package.json', {
                paths: [cliContext],
              }),
              '../node_modules'
            )
          )
        } catch (e) {}
      }
    )
    paths.push(...pathSet)
    debug('uni-paths')(paths)
  }
}

export function getBuiltInPaths() {
  if (!paths.length) {
    initPaths()
fxy060608's avatar
fxy060608 已提交
79
  }
fxy060608's avatar
fxy060608 已提交
80 81 82 83 84
  return paths
}

export function resolveBuiltIn(path: string) {
  return require.resolve(path, { paths: getBuiltInPaths() })
fxy060608's avatar
fxy060608 已提交
85
}
fxy060608's avatar
fxy060608 已提交
86 87 88 89

export function normalizeIdentifier(str: string) {
  return capitalize(camelize(str.replace(/\//g, '-')))
}
fxy060608's avatar
fxy060608 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

export function normalizePagePath(pagePath: string, platform: UniApp.PLATFORM) {
  const absoltePagePath = path.resolve(process.env.UNI_INPUT_DIR, pagePath)
  let extnames = PAGE_EXTNAME
  if (platform === 'app') {
    extnames = PAGE_EXTNAME_APP
  }
  for (let i = 0; i < extnames.length; i++) {
    const extname = extnames[i]
    if (fs.existsSync(absoltePagePath + extname)) {
      return pagePath + extname
    }
  }
  console.error(`${pagePath} not found`)
}
fxy060608's avatar
fxy060608 已提交
105

fxy060608's avatar
fxy060608 已提交
106 107
export function removeExt(str: string) {
  return str.split('?')[0].replace(/\.\w+$/g, '')
fxy060608's avatar
fxy060608 已提交
108
}
fxy060608's avatar
fxy060608 已提交
109 110 111 112 113 114 115 116 117 118 119 120

const NODE_MODULES_REGEX = /(\.\.\/)?node_modules/g

export function normalizeNodeModules(str: string) {
  str = normalizePath(str).replace(NODE_MODULES_REGEX, 'node-modules')
  // HBuilderX 内置模块路径转换
  str = str.replace(/.*\/plugins\/uniapp-cli\/node[-_]modules/, 'node-modules')
  if (process.env.UNI_PLATFORM === 'mp-alipay') {
    str = str.replace('node-modules/@', 'node-modules/npm-scope-')
  }
  return str
}
fxy060608's avatar
fxy060608 已提交
121 122 123 124 125

export function normalizeMiniProgramFilename(
  filename: string,
  inputDir?: string
) {
fxy060608's avatar
fxy060608 已提交
126
  if (!inputDir || !path.isAbsolute(filename)) {
fxy060608's avatar
fxy060608 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    return normalizeNodeModules(filename)
  }
  return normalizeNodeModules(path.relative(inputDir, filename))
}

export function createUniVueTransformAssetUrls(
  base: string
): SFCTemplateCompileOptions['transformAssetUrls'] {
  return {
    base,
    tags: {
      audio: ['src'],
      video: ['src', 'poster'],
      img: ['src'],
      image: ['src'],
      'cover-image': ['src'],
      // h5
      'v-uni-audio': ['src'],
      'v-uni-video': ['src', 'poster'],
      'v-uni-image': ['src'],
      'v-uni-cover-image': ['src'],
      // nvue
      'u-image': ['src'],
      'u-video': ['src', 'poster'],
    },
  }
}