vite.config.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import path, { resolve } from 'node:path'
  2. import dayjs from 'dayjs'
  3. import { defineConfig, loadEnv } from 'vite'
  4. import Uni from '@dcloudio/vite-plugin-uni'
  5. // @see https://uni-helper.js.org/vite-plugin-uni-pages
  6. import UniPages, { PageContext } 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. // @see https://unocss.dev/
  15. import UnoCSS from 'unocss/vite'
  16. import AutoImport from 'unplugin-auto-import/vite'
  17. import { visualizer } from 'rollup-plugin-visualizer'
  18. import ViteRestart from 'vite-plugin-restart'
  19. import { slimMPPlugin, generatePageConfig } from './vitePlugin'
  20. // https://vitejs.dev/config/
  21. export default ({ command, mode }) => {
  22. // console.log(mode === process.env.NODE_ENV) // true
  23. // mode: 区分生产环境还是开发环境
  24. console.log('command, mode -> ', command, mode)
  25. // pnpm dev:h5 时得到 => serve development
  26. // pnpm build:h5 时得到 => build production
  27. // pnpm dev:mp-weixin 时得到 => build development (注意区别,command为build)
  28. // pnpm build:mp-weixin 时得到 => build production
  29. // pnpm dev:app 时得到 => build development (注意区别,command为build)
  30. // pnpm build:app 时得到 => build production
  31. // dev 和 build 命令可以分别使用 .env.development 和 .env.production 的环境变量
  32. const { UNI_PLATFORM } = process.env
  33. console.log('UNI_PLATFORM -> ', UNI_PLATFORM) // 得到 mp-weixin, h5, app 等
  34. const env = loadEnv(mode, path.resolve(process.cwd(), 'env'))
  35. const {
  36. VITE_APP_PORT,
  37. VITE_SERVER_BASEURL,
  38. VITE_DELETE_CONSOLE,
  39. VITE_SHOW_SOURCEMAP,
  40. VITE_APP_PROXY,
  41. VITE_APP_PROXY_PREFIX,
  42. } = env
  43. console.log('环境变量 env -> ', env)
  44. const config = defineConfig({
  45. envDir: './env', // 自定义env目录
  46. plugins: [
  47. slimMPPlugin(),
  48. UniPages({
  49. exclude: ['**/components/**/**.*'],
  50. homePage: 'pages/index/index',
  51. // routeBlockLang: 'json5', // 虽然设了默认值,但是vue文件还是要加上 lang="json5", 这样才能很好地格式化
  52. // homePage 通过 vue 文件的 route-block 的type="home"来设定
  53. // pages 目录为 src/pages,分包目录不能配置在pages目录下
  54. subPackages: ['src/pagesSubExample'], // 是个数组,可以配置多个,但是不能为pages里面的目录
  55. // dts: 'src/types/uni-pages.d.ts',
  56. dts: false,
  57. // debug: true,
  58. // onBeforeScanPages(ctx) {
  59. // const common = require('./scripts/common.js')
  60. // common.files.write(
  61. // common.files.getPath('temp/onBeforeScanPages.json'),
  62. // JSON.stringify(ctx),
  63. // )
  64. // },
  65. onBeforeWriteFile(ctx) {
  66. generatePageConfig(ctx)
  67. },
  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: [
  89. 'vue',
  90. 'uni-app',
  91. {
  92. // import ay from '@/utils/container';
  93. '@/utils/container': [['default', 'ay']],
  94. '@/utils/api/web': [['default', 'webapi']],
  95. '@/utils/store': [['default', 'store']],
  96. '@/utils/config': [['default', 'config']],
  97. '@/utils/func': [['default', 'func']],
  98. '@/utils/aop': [['default', 'aop']],
  99. },
  100. ],
  101. dts: 'src/types/auto-import.d.ts',
  102. dirs: ['src/enums'], // 自动导入
  103. eslintrc: { enabled: true },
  104. vueTemplate: true, // default false
  105. }),
  106. ViteRestart({
  107. // 通过这个插件,在修改vite.config.js文件则不需要重新运行也生效配置
  108. restart: ['vite.config.js'],
  109. }),
  110. // h5环境增加 BUILD_TIME 和 BUILD_BRANCH
  111. UNI_PLATFORM === 'h5' && {
  112. name: 'html-transform',
  113. transformIndexHtml(html) {
  114. return html.replace('%BUILD_TIME%', dayjs().format('YYYY-MM-DD HH:mm:ss'))
  115. },
  116. },
  117. // 打包分析插件,h5 + 生产环境才弹出
  118. UNI_PLATFORM === 'h5' &&
  119. mode === 'production' &&
  120. visualizer({
  121. filename: './node_modules/.cache/visualizer/stats.html',
  122. open: true,
  123. gzipSize: true,
  124. brotliSize: true,
  125. }),
  126. ],
  127. define: {
  128. __UNI_PLATFORM__: JSON.stringify(UNI_PLATFORM),
  129. __VITE_APP_PROXY__: JSON.stringify(VITE_APP_PROXY),
  130. },
  131. css: {
  132. preprocessorOptions: {
  133. scss: {
  134. additionalData: `@import '/src/style/variables.scss';`,
  135. },
  136. },
  137. postcss: {
  138. plugins: [
  139. // autoprefixer({
  140. // // 指定目标浏览器
  141. // overrideBrowserslist: ['> 1%', 'last 2 versions'],
  142. // }),
  143. ],
  144. },
  145. },
  146. resolve: {
  147. alias: {
  148. '@': path.join(process.cwd(), './src'),
  149. '@img': path.join(process.cwd(), './src/static/images'),
  150. },
  151. },
  152. server: {
  153. host: '0.0.0.0',
  154. hmr: true,
  155. port: Number.parseInt(VITE_APP_PORT, 10),
  156. // 仅 H5 端生效,其他端不生效(其他端走build,不走devServer)
  157. proxy: JSON.parse(VITE_APP_PROXY)
  158. ? {
  159. [VITE_APP_PROXY_PREFIX]: {
  160. target: VITE_SERVER_BASEURL,
  161. changeOrigin: true,
  162. rewrite: (path) => path.replace(new RegExp(`^${VITE_APP_PROXY_PREFIX}`), ''),
  163. },
  164. }
  165. : undefined,
  166. },
  167. build: {
  168. // 方便非h5端调试
  169. sourcemap: UNI_PLATFORM === 'h5' && VITE_SHOW_SOURCEMAP === 'true', // 默认是false
  170. target: 'es6',
  171. // 开发环境不用压缩
  172. minify: mode === 'development' ? false : 'terser',
  173. terserOptions: {
  174. compress: {
  175. drop_console: VITE_DELETE_CONSOLE === 'true',
  176. drop_debugger: true,
  177. },
  178. },
  179. },
  180. })
  181. return config
  182. }