utils.ts 4.7 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

fxy060608's avatar
fxy060608 已提交
22 23 24
export function relativeFile(from: string, to: string) {
  return normalizePath(path.relative(path.dirname(from), to))
}
雪洛's avatar
雪洛 已提交
25
export function checkElementNodeTag(
26
  node: RootNode | TemplateChildNode | null | undefined,
雪洛's avatar
雪洛 已提交
27 28
  tag: string
): node is ElementNode {
29
  return !!node && node.type === NodeTypes.ELEMENT && node.tag === tag
雪洛's avatar
雪洛 已提交
30 31
}

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

fxy060608's avatar
fxy060608 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
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[] = []

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
function resolveNodeModulePath(modulePath: string) {
  const nodeModulesPaths: string[] = []
  const nodeModulesPath = path.join(modulePath, 'node_modules')
  if (fs.existsSync(nodeModulesPath)) {
    nodeModulesPaths.push(nodeModulesPath)
  }
  const index = modulePath.lastIndexOf('node_modules')
  if (index > -1) {
    nodeModulesPaths.push(
      path.join(modulePath.substr(0, index), 'node_modules')
    )
  }
  return nodeModulesPaths
}

fxy060608's avatar
fxy060608 已提交
70 71 72 73 74 75 76
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) => {
77
        let pkgPath: string = ''
fxy060608's avatar
fxy060608 已提交
78
        try {
79 80 81
          pkgPath = require.resolve(ownerModule + '/package.json', {
            paths: [cliContext],
          })
fxy060608's avatar
fxy060608 已提交
82
        } catch (e) {}
83 84 85 86 87 88 89
        if (pkgPath) {
          resolveNodeModulePath(path.dirname(pkgPath)).forEach(
            (nodeModulePath) => {
              pathSet.add(nodeModulePath)
            }
          )
        }
fxy060608's avatar
fxy060608 已提交
90 91 92 93 94 95 96 97 98 99
      }
    )
    paths.push(...pathSet)
    debug('uni-paths')(paths)
  }
}

export function getBuiltInPaths() {
  if (!paths.length) {
    initPaths()
fxy060608's avatar
fxy060608 已提交
100
  }
fxy060608's avatar
fxy060608 已提交
101 102 103 104 105
  return paths
}

export function resolveBuiltIn(path: string) {
  return require.resolve(path, { paths: getBuiltInPaths() })
fxy060608's avatar
fxy060608 已提交
106
}
fxy060608's avatar
fxy060608 已提交
107 108 109 110

export function normalizeIdentifier(str: string) {
  return capitalize(camelize(str.replace(/\//g, '-')))
}
fxy060608's avatar
fxy060608 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

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 已提交
126

fxy060608's avatar
fxy060608 已提交
127 128
export function removeExt(str: string) {
  return str.split('?')[0].replace(/\.\w+$/g, '')
fxy060608's avatar
fxy060608 已提交
129
}
fxy060608's avatar
fxy060608 已提交
130 131 132 133 134 135 136 137 138 139 140 141

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 已提交
142 143 144 145 146

export function normalizeMiniProgramFilename(
  filename: string,
  inputDir?: string
) {
fxy060608's avatar
fxy060608 已提交
147
  if (!inputDir || !path.isAbsolute(filename)) {
fxy060608's avatar
fxy060608 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    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'],
    },
  }
}