vite.config.ts 6.7 KB

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