vite.config.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. // @see https://uni-helper.js.org/vite-plugin-uni-pages
  6. import UniPages from '@uni-helper/vite-plugin-uni-pages'
  7. // @see https://uni-helper.js.org/vite-plugin-uni-layouts
  8. import UniLayouts from '@uni-helper/vite-plugin-uni-layouts'
  9. // @see https://github.com/uni-helper/vite-plugin-uni-platform
  10. // 需要与 @uni-helper/vite-plugin-uni-pages 插件一起使用
  11. import UniPlatform from '@uni-helper/vite-plugin-uni-platform'
  12. // @see https://github.com/uni-helper/vite-plugin-uni-manifest
  13. import UniManifest from '@uni-helper/vite-plugin-uni-manifest'
  14. /**
  15. * 分包优化、模块异步跨包调用、组件异步跨包引用
  16. * @see https://github.com/uni-ku/bundle-optimizer
  17. */
  18. import Optimization from '@uni-ku/bundle-optimizer'
  19. import { visualizer } from 'rollup-plugin-visualizer'
  20. import AutoImport from 'unplugin-auto-import/vite'
  21. import ViteRestart from 'vite-plugin-restart'
  22. import { copyNativeRes } from './vite-plugins/copyNativeRes'
  23. import Components from '@uni-helper/vite-plugin-uni-components'
  24. // https://vitejs.dev/config/
  25. export default async ({ command, mode }) => {
  26. // @see https://unocss.dev/
  27. const UnoCSS = (await import('unocss/vite')).default
  28. // console.log(mode === process.env.NODE_ENV) // true
  29. // mode: 区分生产环境还是开发环境
  30. console.log('command, mode -> ', command, mode)
  31. // pnpm dev:h5 时得到 => serve development
  32. // pnpm build:h5 时得到 => build production
  33. // pnpm dev:mp-weixin 时得到 => build development (注意区别,command为build)
  34. // pnpm build:mp-weixin 时得到 => build production
  35. // pnpm dev:app 时得到 => build development (注意区别,command为build)
  36. // pnpm build:app 时得到 => build production
  37. // dev 和 build 命令可以分别使用 .env.development 和 .env.production 的环境变量
  38. const { UNI_PLATFORM } = process.env
  39. console.log('UNI_PLATFORM -> ', UNI_PLATFORM) // 得到 mp-weixin, h5, app 等
  40. const env = loadEnv(mode, path.resolve(process.cwd(), 'env'))
  41. const {
  42. VITE_APP_PORT,
  43. VITE_SERVER_BASEURL,
  44. VITE_DELETE_CONSOLE,
  45. VITE_SHOW_SOURCEMAP,
  46. VITE_APP_PROXY,
  47. VITE_APP_PROXY_PREFIX,
  48. } = env
  49. console.log('环境变量 env -> ', env)
  50. return defineConfig({
  51. envDir: './env', // 自定义env目录
  52. plugins: [
  53. UniPages({
  54. exclude: ['**/components/**/**.*'],
  55. routeBlockLang: 'json5', // 虽然设了默认值,但是vue文件还是要加上 lang="json5", 这样才能很好地格式化
  56. // homePage 通过 vue 文件的 route-block 的type="home"来设定
  57. // pages 目录为 src/pages,分包目录不能配置在pages目录下
  58. // subPackages: ['src/pages-sub'], // 是个数组,可以配置多个,但是不能为pages里面的目录
  59. dts: 'src/types/uni-pages.d.ts',
  60. }),
  61. UniLayouts(),
  62. UniPlatform(),
  63. UniManifest(),
  64. // UniXXX 需要在 Uni 之前引入
  65. {
  66. // 临时解决 dcloudio 官方的 @dcloudio/uni-mp-compiler 出现的编译 BUG
  67. // 参考 github issue: https://github.com/dcloudio/uni-app/issues/4952
  68. // 自定义插件禁用 vite:vue 插件的 devToolsEnabled,强制编译 vue 模板时 inline 为 true
  69. name: 'fix-vite-plugin-vue',
  70. configResolved(config) {
  71. const plugin = config.plugins.find((p) => p.name === 'vite:vue')
  72. if (plugin && plugin.api && plugin.api.options) {
  73. plugin.api.options.devToolsEnabled = false
  74. }
  75. },
  76. },
  77. UnoCSS(),
  78. AutoImport({
  79. imports: ['vue', 'uni-app'],
  80. dts: 'src/types/auto-import.d.ts',
  81. dirs: ['src/hooks'], // 自动导入 hooks
  82. vueTemplate: true, // default false
  83. }),
  84. // Optimization 插件需要 page.json 文件,故应在 UniPages 插件之后执行
  85. Optimization({
  86. enable: {
  87. optimization: true,
  88. 'async-import': true,
  89. 'async-component': true,
  90. },
  91. dts: {
  92. base: 'src/types',
  93. },
  94. logger: false,
  95. }),
  96. ViteRestart({
  97. // 通过这个插件,在修改vite.config.js文件则不需要重新运行也生效配置
  98. restart: ['vite.config.js'],
  99. }),
  100. // h5环境增加 BUILD_TIME 和 BUILD_BRANCH
  101. UNI_PLATFORM === 'h5' && {
  102. name: 'html-transform',
  103. transformIndexHtml(html) {
  104. return html.replace('%BUILD_TIME%', dayjs().format('YYYY-MM-DD HH:mm:ss'))
  105. },
  106. },
  107. // 打包分析插件,h5 + 生产环境才弹出
  108. UNI_PLATFORM === 'h5' &&
  109. mode === 'production' &&
  110. visualizer({
  111. filename: './node_modules/.cache/visualizer/stats.html',
  112. open: true,
  113. gzipSize: true,
  114. brotliSize: true,
  115. }),
  116. // 只有在 app 平台时才启用 copyNativeRes 插件
  117. UNI_PLATFORM === 'app' && copyNativeRes(),
  118. Components({
  119. extensions: ['vue'],
  120. deep: true, // 是否递归扫描子目录,
  121. directoryAsNamespace: false, // 是否把目录名作为命名空间前缀,true 时组件名为 目录名+组件名,
  122. dts: 'src/types/components.d.ts', // 自动生成的组件类型声明文件路径(用于 TypeScript 支持)
  123. }),
  124. Uni(),
  125. ],
  126. define: {
  127. __UNI_PLATFORM__: JSON.stringify(UNI_PLATFORM),
  128. __VITE_APP_PROXY__: JSON.stringify(VITE_APP_PROXY),
  129. },
  130. css: {
  131. postcss: {
  132. plugins: [
  133. // autoprefixer({
  134. // // 指定目标浏览器
  135. // overrideBrowserslist: ['> 1%', 'last 2 versions'],
  136. // }),
  137. ],
  138. },
  139. },
  140. resolve: {
  141. alias: {
  142. '@': path.join(process.cwd(), './src'),
  143. '@img': path.join(process.cwd(), './src/static/images'),
  144. },
  145. },
  146. server: {
  147. host: '0.0.0.0',
  148. hmr: true,
  149. port: Number.parseInt(VITE_APP_PORT, 10),
  150. // 仅 H5 端生效,其他端不生效(其他端走build,不走devServer)
  151. proxy: JSON.parse(VITE_APP_PROXY)
  152. ? {
  153. [VITE_APP_PROXY_PREFIX]: {
  154. target: VITE_SERVER_BASEURL,
  155. changeOrigin: true,
  156. rewrite: (path) => path.replace(new RegExp(`^${VITE_APP_PROXY_PREFIX}`), ''),
  157. },
  158. }
  159. : undefined,
  160. },
  161. build: {
  162. // 方便非h5端调试
  163. sourcemap: VITE_SHOW_SOURCEMAP === 'true', // 默认是false
  164. target: 'es6',
  165. // 开发环境不用压缩
  166. minify: mode === 'development' ? false : 'terser',
  167. terserOptions: {
  168. compress: {
  169. drop_console: VITE_DELETE_CONSOLE === 'true',
  170. drop_debugger: true,
  171. },
  172. },
  173. },
  174. })
  175. }