普兆健康管家后端代码仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

231 lines
8.5 KiB

4 days ago
  1. import Uni from '@dcloudio/vite-plugin-uni'
  2. import dayjs from 'dayjs'
  3. import path from 'node:path'
  4. import { defineConfig, loadEnv } from 'vite'
  5. import fs from 'node:fs'
  6. import { generateComponentTypes } from './vite-plugins/generateComponentTypes'
  7. console.log('进入 vite')
  8. // @see https://uni-helper.js.org/vite-plugin-uni-pages
  9. import UniPages from '@uni-helper/vite-plugin-uni-pages'
  10. // @see https://uni-helper.js.org/vite-plugin-uni-layouts
  11. import UniLayouts from '@uni-helper/vite-plugin-uni-layouts'
  12. // @see https://github.com/uni-helper/vite-plugin-uni-platform
  13. // 需要与 @uni-helper/vite-plugin-uni-pages 插件一起使用
  14. import UniPlatform from '@uni-helper/vite-plugin-uni-platform'
  15. // @see https://github.com/uni-helper/vite-plugin-uni-manifest
  16. import UniManifest from '@uni-helper/vite-plugin-uni-manifest'
  17. // @see https://unocss.dev/
  18. import { visualizer } from 'rollup-plugin-visualizer'
  19. import UnoCSS from 'unocss/vite'
  20. import AutoImport from 'unplugin-auto-import/vite'
  21. import ViteRestart from 'vite-plugin-restart'
  22. import { copyNativeRes } from './vite-plugins/copyNativeRes'
  23. import { viteMockServe } from 'vite-plugin-mock'
  24. // https://vitejs.dev/config/
  25. export default ({ command, mode }) => {
  26. // console.log(mode === process.env.NODE_ENV) // true
  27. // mode: 区分生产环境还是开发环境
  28. console.log('command, mode -> ', command, mode)
  29. // pnpm dev:h5 时得到 => serve development
  30. // pnpm build:h5 时得到 => build production
  31. // pnpm dev:mp-weixin 时得到 => build development (注意区别,command为build)
  32. // pnpm build:mp-weixin 时得到 => build production
  33. // pnpm dev:app 时得到 => build development (注意区别,command为build)
  34. // pnpm build:app 时得到 => build production
  35. // dev 和 build 命令可以分别使用 .env.development 和 .env.production 的环境变量
  36. const { UNI_PLATFORM } = process.env
  37. console.log('UNI_PLATFORM -> ', UNI_PLATFORM) // 得到 mp-weixin, h5, app 等
  38. const env = loadEnv(mode, path.resolve(process.cwd(), 'env'))
  39. const {
  40. VITE_APP_PORT,
  41. VITE_SERVER_BASEURL,
  42. VITE_DELETE_CONSOLE,
  43. VITE_SHOW_SOURCEMAP,
  44. VITE_APP_PROXY,
  45. VITE_APP_PROXY_PREFIX,
  46. VITE_USE_MOCK,
  47. } = env
  48. console.log('环境变量 env -> ', env)
  49. // 在h5平台把vite环境变量提取出来替换成window上的属性
  50. const define = UNI_PLATFORM === 'h5' && mode === 'production' ? createDynamicDefine(env) : {}
  51. return defineConfig({
  52. envDir: './env', // 自定义env目录
  53. plugins: [
  54. generateComponentTypes(),
  55. UniPages({
  56. exclude: ['**/components/**/**.*'],
  57. routeBlockLang: 'json5', // 虽然设了默认值,但是vue文件还是要加上 lang="json5", 这样才能很好地格式化
  58. // homePage 通过 vue 文件的 route-block 的type="home"来设定
  59. // pages 目录为 src/pages,分包目录不能配置在pages目录下
  60. subPackages: [
  61. 'src/pages-home',
  62. 'src/pages-message',
  63. 'src/pages-user',
  64. 'src/pages-work',
  65. 'src/pages-sub',
  66. ], // 是个数组,可以配置多个,但是不能为pages里面的目录
  67. dts: 'src/types/uni-pages.d.ts',
  68. }),
  69. UniLayouts(),
  70. UniPlatform(),
  71. UniManifest(),
  72. // UniXXX 需要在 Uni 之前引入
  73. Uni(),
  74. {
  75. // 临时解决 dcloudio 官方的 @dcloudio/uni-mp-compiler 出现的编译 BUG
  76. // 参考 github issue: https://github.com/dcloudio/uni-app/issues/4952
  77. // 自定义插件禁用 vite:vue 插件的 devToolsEnabled,强制编译 vue 模板时 inline 为 true
  78. name: 'fix-vite-plugin-vue',
  79. configResolved(config) {
  80. const plugin = config.plugins.find((p) => p.name === 'vite:vue')
  81. if (plugin && plugin.api && plugin.api.options) {
  82. plugin.api.options.devToolsEnabled = false
  83. }
  84. },
  85. },
  86. UnoCSS(),
  87. AutoImport({
  88. imports: ['vue', 'uni-app'],
  89. dts: 'src/types/auto-import.d.ts',
  90. dirs: ['src/hooks'], // 自动导入 hooks
  91. eslintrc: { enabled: true },
  92. vueTemplate: true, // default false
  93. }),
  94. ViteRestart({
  95. // 通过这个插件,在修改vite.config.js文件则不需要重新运行也生效配置
  96. restart: ['vite.config.js'],
  97. }),
  98. // h5环境增加 BUILD_TIME 和 BUILD_BRANCH
  99. UNI_PLATFORM === 'h5' && {
  100. name: 'html-transform',
  101. transformIndexHtml(html) {
  102. return html.replace('%BUILD_TIME%', dayjs().format('YYYY-MM-DD HH:mm:ss'))
  103. },
  104. },
  105. // 打包分析插件,h5 + 生产环境才弹出
  106. UNI_PLATFORM === 'h5' &&
  107. mode === 'production' &&
  108. visualizer({
  109. filename: './node_modules/.cache/visualizer/stats.html',
  110. open: true,
  111. gzipSize: true,
  112. brotliSize: true,
  113. }),
  114. // 只有在 app 平台时才启用 copyNativeRes 插件
  115. UNI_PLATFORM === 'app' && copyNativeRes(),
  116. viteMockServe({
  117. // 指定 mock 文件目录
  118. mockPath: './mock',
  119. // 开发服务器才启用mock数据
  120. enable: mode === 'development' && JSON.parse(VITE_USE_MOCK),
  121. }),
  122. UNI_PLATFORM === 'h5' && mode === 'production' && createEnvConfigPlugin(),
  123. ],
  124. define: {
  125. __UNI_PLATFORM__: JSON.stringify(UNI_PLATFORM),
  126. __VITE_APP_PROXY__: JSON.stringify(VITE_APP_PROXY),
  127. ...define,
  128. },
  129. css: {
  130. postcss: {
  131. plugins: [
  132. // autoprefixer({
  133. // // 指定目标浏览器
  134. // overrideBrowserslist: ['> 1%', 'last 2 versions'],
  135. // }),
  136. ],
  137. },
  138. },
  139. resolve: {
  140. alias: {
  141. '@': path.join(process.cwd(), './src'),
  142. '@img': path.join(process.cwd(), './src/static/images'),
  143. },
  144. },
  145. server: {
  146. host: '0.0.0.0',
  147. hmr: true,
  148. port: Number.parseInt(VITE_APP_PORT, 10),
  149. // 仅 H5 端生效,其他端不生效(其他端走build,不走devServer)
  150. proxy: JSON.parse(VITE_APP_PROXY)
  151. ? {
  152. [VITE_APP_PROXY_PREFIX]: {
  153. target: VITE_SERVER_BASEURL,
  154. changeOrigin: true,
  155. rewrite: (path) => path.replace(new RegExp(`^${VITE_APP_PROXY_PREFIX}`), ''),
  156. },
  157. }
  158. : undefined,
  159. },
  160. build: {
  161. // 方便非h5端调试
  162. sourcemap: VITE_SHOW_SOURCEMAP === 'true', // 默认是false
  163. target: 'es6',
  164. // 开发环境不用压缩
  165. minify: mode === 'development' ? false : 'terser',
  166. terserOptions: {
  167. compress: {
  168. drop_console: VITE_DELETE_CONSOLE === 'true',
  169. drop_debugger: true,
  170. },
  171. },
  172. },
  173. })
  174. }
  175. // 环境变量映射到window上的属性
  176. function createDynamicDefine(envVars) {
  177. return Object.keys(envVars).reduce((acc, key) => {
  178. if (key.startsWith('VITE_')) {
  179. acc[`import.meta.env.${key}`] = `window.__APP_CONFIG__.${key}`
  180. }
  181. return acc
  182. }, {})
  183. }
  184. function createEnvConfigPlugin() {
  185. let mode = 'production'
  186. let envDir = process.cwd()
  187. return {
  188. name: 'dynamic-env',
  189. config(config, { mode: configMode }) {
  190. mode = configMode || 'production'
  191. envDir = config.envDir || envDir
  192. },
  193. async writeBundle(options) {
  194. const env = loadEnv(mode, path.resolve(process.cwd(), 'env'))
  195. delete env['VITE_ROOT_DIR']
  196. // 生成动态配置文件
  197. const configContent = `window.__APP_CONFIG__ = ${JSON.stringify(env)};`
  198. const outputDir = options.dir || path.resolve(envDir, 'dist')
  199. const configPath = path.join(outputDir, 'app.config.js')
  200. // 写入配置文件
  201. fs.writeFileSync(configPath, configContent, 'utf-8')
  202. // 修改 index.html 注入脚本
  203. const indexPath = path.join(outputDir, 'index.html')
  204. if (fs.existsSync(indexPath)) {
  205. let html = fs.readFileSync(indexPath, 'utf-8')
  206. // update-begin-author:liaozhiyang date:2025-05-27 for:【issues/87】h5打包部署后,Oauth2认证后无法正确引入app.config.js文件
  207. let prefix = '/'
  208. if (env.VITE_APP_PUBLIC_BASE) {
  209. prefix = env.VITE_APP_PUBLIC_BASE
  210. }
  211. if (prefix.endsWith('/')) {
  212. prefix = prefix.slice(0, -1)
  213. }
  214. const scriptTag = `<script src="${prefix}/app.config.js"></script>`
  215. // update-end-author:liaozhiyang date:2025-05-27 for:【issues/87】h5打包部署后,Oauth2认证后无法正确引入app.config.js文件
  216. if (!html.includes('app.config.js')) {
  217. html = html.replace('</title>', `</title> \n ${scriptTag}`)
  218. fs.writeFileSync(indexPath, html, 'utf-8')
  219. }
  220. }
  221. },
  222. }
  223. }