vite.config.ts 6.8 KB

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