resolve.ts 4.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8
import fs from 'fs'

import path from 'path'
import debug from 'debug'
import resolve from 'resolve'
import { once } from '@dcloudio/uni-shared'

import { normalizePath } from './utils'
fxy060608's avatar
fxy060608 已提交
9
import { isInHBuilderX } from './hbx/env'
10 11 12 13 14
import { extensions } from './constants'

export function requireResolve(filename: string, basedir: string) {
  return resolveWithSymlinks(filename, basedir)
}
fxy060608's avatar
fxy060608 已提交
15 16 17 18

function resolveWithSymlinks(id: string, basedir: string): string {
  return resolve.sync(id, {
    basedir,
19
    extensions,
fxy060608's avatar
fxy060608 已提交
20 21 22 23
    // necessary to work with pnpm
    preserveSymlinks: true,
  })
}
fxy060608's avatar
fxy060608 已提交
24

fxy060608's avatar
fxy060608 已提交
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
export function relativeFile(from: string, to: string) {
  const relativePath = normalizePath(path.relative(path.dirname(from), to))
  return relativePath.startsWith('.') ? relativePath : './' + relativePath
}

export const resolveMainPathOnce = once((inputDir: string) => {
  const mainTsPath = path.resolve(inputDir, 'main.ts')
  if (fs.existsSync(mainTsPath)) {
    return normalizePath(mainTsPath)
  }
  return normalizePath(path.resolve(inputDir, 'main.js'))
})

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

const paths: string[] = []

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) {
fxy060608's avatar
fxy060608 已提交
50
    nodeModulesPaths.push(path.join(modulePath.slice(0, index), 'node_modules'))
fxy060608's avatar
fxy060608 已提交
51 52 53 54 55 56 57 58 59
  }
  return nodeModulesPaths
}

function initPaths() {
  const cliContext = process.env.UNI_CLI_CONTEXT
  if (cliContext) {
    const pathSet = new Set<string>()
    pathSet.add(path.join(cliContext, 'node_modules'))
fxy060608's avatar
fxy060608 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
    if (!isInHBuilderX()) {
      ;[`@dcloudio/uni-` + process.env.UNI_PLATFORM, ...ownerModules].forEach(
        (ownerModule) => {
          let pkgPath: string = ''
          try {
            pkgPath = require.resolve(ownerModule + '/package.json', {
              paths: [cliContext],
            })
          } catch (e) {}
          if (pkgPath) {
            resolveNodeModulePath(path.dirname(pkgPath)).forEach(
              (nodeModulePath) => {
                pathSet.add(nodeModulePath)
              }
            )
          }
fxy060608's avatar
fxy060608 已提交
76
        }
fxy060608's avatar
fxy060608 已提交
77 78
      )
    }
fxy060608's avatar
fxy060608 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    paths.push(...pathSet)
    debug('uni-paths')(paths)
  }
}

export function getBuiltInPaths() {
  if (!paths.length) {
    initPaths()
  }
  return paths
}

export function resolveBuiltIn(path: string) {
  return require.resolve(path, { paths: getBuiltInPaths() })
}

fxy060608's avatar
fxy060608 已提交
95 96 97 98 99 100 101
export function resolveVueI18nRuntime() {
  return path.resolve(
    __dirname,
    '../lib/vue-i18n/dist/vue-i18n.runtime.esm-bundler.js'
  )
}

fxy060608's avatar
fxy060608 已提交
102 103 104
let componentsLibPath: string = ''
export function resolveComponentsLibPath() {
  if (!componentsLibPath) {
fxy060608's avatar
fxy060608 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118
    if (isInHBuilderX()) {
      componentsLibPath = path.join(
        resolveBuiltIn('@dcloudio/uni-components/package.json'),
        '../lib'
      )
    } else {
      componentsLibPath = path.join(
        resolveWithSymlinks(
          '@dcloudio/uni-components/package.json',
          process.env.UNI_INPUT_DIR
        ),
        '../lib'
      )
    }
fxy060608's avatar
fxy060608 已提交
119 120 121
  }
  return componentsLibPath
}
fxy060608's avatar
fxy060608 已提交
122 123 124 125 126 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 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

// 仅限 root/uni_modules/test-plugin | root/utssdk/test-plugin 格式
export function resolveUtsModule(
  id: string,
  importer: string,
  platform: typeof process.env.UNI_UTS_PLATFORM
) {
  id = path.resolve(importer, id)
  if (id.includes('utssdk') || id.includes('uni_modules')) {
    const parts = normalizePath(id).split('/')
    const parentDir = parts[parts.length - 2]
    if (parentDir === 'uni_modules' || parentDir === 'utssdk') {
      const index = path.resolve(id, 'index.uts')
      if (fs.existsSync(index)) {
        return index
      }
      if (
        parentDir === 'uni_modules' &&
        !fs.existsSync(path.join(id, 'utssdk'))
      ) {
        // uni_modules/test-plugin/utssdk不存在
        return
      }
      const platformDir = path.resolve(
        id,
        parentDir === 'uni_modules' ? 'utssdk' : '',
        platform
      )
      // App平台仅支持 uts
      if (platform === 'app-android' || platform === 'app-ios') {
        return resolveUtsFile(platformDir, ['.uts'])
      }
      return resolveUtsFile(platformDir)
    }
  }
}

function resolveUtsFile(
  dir: string,
  extensions: string[] = ['.uts', '.ts', '.js']
) {
  for (let i = 0; i < extensions.length; i++) {
    const indexFile = path.join(dir, 'index' + extensions[i])
    if (fs.existsSync(indexFile)) {
      return indexFile
    }
  }
}