uni.plugin.ts 5.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
import path from 'path'
import { sync } from 'fast-glob'
fxy060608's avatar
fxy060608 已提交
3
import { isArray } from '@vue/shared'
4 5
import { once } from '@dcloudio/uni-shared'
import {
雪洛's avatar
雪洛 已提交
6
  isSsr,
雪洛's avatar
雪洛 已提交
7
  defineUniMainJsPlugin,
8
  COMMON_EXCLUDE,
fxy060608's avatar
fxy060608 已提交
9
  isInHybridNVue,
10 11
  uniViteInjectPlugin,
  UniVitePlugin,
fxy060608's avatar
fxy060608 已提交
12
  isInHBuilderX,
雪洛's avatar
雪洛 已提交
13
  isEnableSecureNetwork
14 15 16 17 18
} from '@dcloudio/uni-cli-shared'

import { uniValidateFunctionPlugin } from './validateFunction'

const uniCloudSpaces: {
19
  provider?: string
20 21 22 23 24 25
  id: string
  name: string
  clientSecret?: string
  apiEndpoint?: string
}[] = []

fxy060608's avatar
fxy060608 已提交
26 27 28
const initUniCloudEnvOnce = once(initUniCloudEnv)

initUniCloudEnvOnce()
29 30 31 32

/**
 * @type {import('vite').Plugin}
 */
fxy060608's avatar
fxy060608 已提交
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
function uniCloudPlugin(): UniVitePlugin {
  return {
    name: 'uni:cloud',
    config(config) {
      const silent = config.build && config.build.ssr ? true : false
      if (silent) {
        return
      }
      const len = uniCloudSpaces.length
      if (!len) {
        return
      }
      if (isInHybridNVue(config)) {
        return
      }
      if (len === 1) {
        console.log(
          `本项目的uniCloud使用的默认服务空间spaceId为:${uniCloudSpaces[0].id}`
        )
      }
      if (
        process.env.UNI_PLATFORM === 'h5' &&
        !process.env.UNI_SUB_PLATFORM &&
        process.env.NODE_ENV === 'production'
      ) {
        console.warn(
雪洛's avatar
雪洛 已提交
59
          '发布H5,需要在uniCloud后台操作,绑定安全域名,否则会因为跨域问题而无法访问。教程参考:https://uniapp.dcloud.net.cn/uniCloud/publish.html#useinh5'
fxy060608's avatar
fxy060608 已提交
60 61 62 63 64 65 66 67 68 69
        )
      }
      return {}
    },
    configureServer(server) {
      if (server.httpServer) {
        server.httpServer.on('listening', () => {
          process.nextTick(() => {
            initUniCloudWarningOnce()
          })
70
        })
fxy060608's avatar
fxy060608 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84
      } else {
        initUniCloudWarningOnce()
      }
    },
    closeBundle() {
      if (process.env.UNI_PLATFORM === 'h5' && !process.env.UNI_SSR_CLIENT) {
        console.log()
        console.log(
          '欢迎将H5站部署到uniCloud前端网页托管平台,高速、免费、安全、省心,详见:'
        )
        console.log('https://uniapp.dcloud.io/uniCloud/hosting')
      }
    },
  }
85 86 87 88 89
}

const initUniCloudWarningOnce = once(() => {
  uniCloudSpaces.length &&
    console.warn(
雪洛's avatar
雪洛 已提交
90
      '当前项目使用了uniCloud,为避免云函数调用跨域问题,建议在HBuilderX内置浏览器里调试,如使用外部浏览器需处理跨域,详见:https://uniapp.dcloud.net.cn/uniCloud/publish.html#useinh5'
91 92 93
    )
})

fxy060608's avatar
fxy060608 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
function checkProjectUniCloudDir() {
  return !!sync(['uniCloud-aliyun', 'uniCloud-tcb'], {
    cwd: isInHBuilderX()
      ? process.env.UNI_INPUT_DIR
      : process.env.UNI_CLI_CONTEXT,
    onlyDirectories: true,
    onlyFiles: false,
    ignore: ['node_modules'],
  }).length
}

function resolveUniCloudModules() {
  return sync('**/uni_modules/*/uniCloud', {
    cwd: process.env.UNI_INPUT_DIR,
    onlyDirectories: true,
    onlyFiles: false,
    ignore: ['node_modules'],
  }).map((dir) => path.dirname(dir))
}

function checkUniModules() {
  if (!checkProjectUniCloudDir()) {
    const uniCloudModules = resolveUniCloudModules()
    if (uniCloudModules.length) {
      console.warn(
        `${uniCloudModules.join(
          ', '
        )} 使用了uniCloud,而项目未启动uniCloud。需在项目点右键创建uniCloud环境`
      )
    }
  }
}

127
function initUniCloudEnv() {
fxy060608's avatar
fxy060608 已提交
128
  checkUniModules()
129 130 131 132 133 134 135 136 137 138 139
  if (process.env.UNI_CLOUD_PROVIDER) {
    const spaces = JSON.parse(process.env.UNI_CLOUD_PROVIDER)
    if (!isArray(spaces)) {
      return
    }
    if (spaces.length) {
      uniCloudSpaces.push(...spaces)
      return
    }
  }
  process.env.UNI_CLOUD_PROVIDER = JSON.stringify([])
140 141 142 143 144
  if (!process.env.UNI_CLOUD_SPACES) {
    return
  }
  try {
    const spaces = JSON.parse(process.env.UNI_CLOUD_SPACES)
fxy060608's avatar
fxy060608 已提交
145
    if (!isArray(spaces)) {
146 147 148 149 150
      return
    }
    spaces.forEach((s) => uniCloudSpaces.push(s))
    process.env.UNI_CLOUD_PROVIDER = JSON.stringify(
      uniCloudSpaces.map((space) => {
151 152 153
        if (space.provider === 'tcb') {
          space.provider = 'tencent'
        }
154 155
        if (space.clientSecret) {
          return {
156
            provider: space.provider || 'aliyun',
157 158 159 160 161 162 163
            spaceName: space.name,
            spaceId: space.id,
            clientSecret: space.clientSecret,
            endpoint: space.apiEndpoint,
          }
        } else {
          return {
164
            provider: space.provider || 'tencent',
165 166 167 168 169 170 171 172 173
            spaceName: space.name,
            spaceId: space.id,
          }
        }
      })
    )
  } catch (e) {}
}

fxy060608's avatar
fxy060608 已提交
174
export default () => [
雪洛's avatar
雪洛 已提交
175 176 177 178
  defineUniMainJsPlugin((opts) => {
    return {
      name: 'uni:cloud',
      enforce: 'pre',
雪洛's avatar
雪洛 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191
      config(config, env) {
        if (isSsr(env.command, config)) {
          return
        }
        const inputDir = process.env.UNI_INPUT_DIR!
        const platform = process.env.UNI_PLATFORM!
        const isSecureNetworkEnabled = isEnableSecureNetwork(inputDir, platform)
        return {
          define: {
            'process.env.UNI_SECURE_NETWORK': isSecureNetworkEnabled,
          },
        }
      },
雪洛's avatar
雪洛 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204
      transform(code, id) {
        if (!opts.filter(id)) {
          return
        }
        if (uniCloudSpaces.length) {
          return {
            code: code + `;import '@dcloudio/uni-cloud';`,
            map: null,
          }
        }
      },
    }
  }),
fxy060608's avatar
fxy060608 已提交
205 206
  uniCloudPlugin(),
  uniViteInjectPlugin('uni:cloud-inject', {
207 208 209 210 211
    exclude: [...COMMON_EXCLUDE],
    uniCloud: ['@dcloudio/uni-cloud', 'default'],
  }),
  uniValidateFunctionPlugin(),
]