vite.config.ts 8.4 KB

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