vite.config.ts 7.0 KB

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